0% found this document useful (0 votes)
142 views48 pages

ICSE Computer Theory QN Bank-2

The document discusses iteration statements in Java including for, while, and do-while loops. It provides examples and explanations of the differences between these loops. Some key points covered include: - While loops check the test expression at the beginning, while do-while loops check it at the bottom after executing the loop body at least once. - The break statement terminates the loop, while continue skips the rest of the current loop iteration. - For loops are preferred when the number of iterations is known, while loops are used when the number depends on a control variable, and do-while loops when the number depends on user input. - Infinite loops have no condition to terminate the loop, while

Uploaded by

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

ICSE Computer Theory QN Bank-2

The document discusses iteration statements in Java including for, while, and do-while loops. It provides examples and explanations of the differences between these loops. Some key points covered include: - While loops check the test expression at the beginning, while do-while loops check it at the bottom after executing the loop body at least once. - The break statement terminates the loop, while continue skips the rest of the current loop iteration. - For loops are preferred when the number of iterations is known, while loops are used when the number depends on a control variable, and do-while loops when the number depends on user input. - Infinite loops have no condition to terminate the loop, while

Uploaded by

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

Iterations

Q. What are iteration statements? Name the iteration statements provided by Java?
Ans: Iteration statements are statements that allows a set of instructions to be executed repeatedly till
some condition is satisfied. The iteration statements provided by Java are: for loop, while loop, do-
while loop.

Q. What is the difference between entry controlled and exit controlled loop?                          
or
What is the difference between while and do-while loop?
Ans: while loop is known as entry controlled loop and do-while loop is known as exit-controlled
loop. The differences between these two loops are: (1) In while loop the test expression is evaluated
at the beginning where as in do-while loop test expression is evaluated at the bottom, after the body
of the loop. (2) In while loop if the test expression is false loop does not continued but in do-while
what ever the test expression the loop execute at least once.

Q. Explain the difference between break and continue with an example.


Ans: Both statements are used as a jump statement. But there is a difference between Break and
Continue statement. The break statement terminate the loop, but the continue statement skip the rest
of the loop statement and continued the next iteration of the loop.e.g. of Break Statementint
i=0;while(i<=10){  i++;  if(i==5)    break;  System.out.println(i);}e.g. of Continue Statementint
i=0;while(i<=10){  i++;  if(i==5)    continue;  System.out.println(i);}

Q. Compare and discuss the suitability of three loops in different situation?


Ans: (i) The for loop should be preferred if number of iteration is known beforehand. (ii) The while
loop should be preferred if the number iteration is dependent upon some control variable. (iii) The
do-while loop should be preferred if the number of iterations is dependent upon user response.

Q. Explain the term for loop with an example.


Ans: In Java the 'for' statement is the most common iterative statement. the general syntax of the for
loop is,for(initialization; test-expression; increment){  body of the loop}This loop is executed at
initial value, condition and increment. Three statement separated by semi colons are placed with in
the parenthesis. for example:for(int i=1;i<=10;i++){  System.out.println(i);}

Q. State one similarity and one difference between while and do-while loop.
Ans: Similarity: In both loops there is a chances to forget the increment statement inside the loop.
Difference: In while loop the test expression is evaluated at the beginning where as in do-while loop
test expression is evaluated at the bottom, after the body of the loop.

Q. What do you meant by an infinite loop? Give an example. [2008]   ORQ. What do you meant
by an endless loop? Give an example.
Ans: Infinite loop is an endless loop whose number of iterations are not fixed.eg: for(;;)    
System.out.println("java");

Q. Differentiate fixed and variable iterative type of loops.


Ans: Fixed type of iterative loop is created when the process is to be repeated for defined number of
times. Variable iterative loop repeats the process till a given condition is true.

Q. Differentiate Null loop and Infinite loop.


Ans: A Null loop does not contains any statement to repeat where as infinite loop repeats execution
of the statements for endless iterations.e.g. of null loops  for(int i=1;i<=10;i++);e.g. for infinite loop 
for(int i=10;i>=1;i++)

Q. What do you mean by delay loop?


Ans: A null loop is also called delay loop which does not repeat the execution of any statement but
keeps the control engaged until the iterations are completed.
Q 1. What is the difference between while and do-while loop ?
Ans, A while loop checks the test expression in the beginning of the loop
before entei
into the loop whereas in do..while the execution of the loop goes once and
then
condition is checked to decide whether the loop should continue or not.
A while loop is not executed at all if the condition is false in the beginning,
when
the do whue loop is executed at least once even if the condition is false in the
beginn
Q 2. Explain the term for loop with an example.
Ans. The for loop is an iteration statement used generally when number of
iterat: are known beforehand- It has the following syntax :
Syntax :
for(initialization expression ;test condition ; updation expression)
{ ' '•'
//loop body

eg : for(i=l;i<=10;i++)
System.out.println(i);
Q 3. What does a break statement do in a loop ? 1
Ans. A break statement terminates the current loop and proceeds to the first
statement that follows the loop. Example :
forCi =l;i<10;i++)

if( i = =5 ) break;
System.out.println(i);

In the above program the loop will break at i = 5 so the output of the program will be: 1 2 3 4

Q 4. Define an empty loop.


Ans. The loop which does not contain any statements in its loop body is known as
empty loop. Example :
for(i=l;i<=100;i++) {}
Q 5. Define an infinite loop.

Ans. The loop that executes endlessly is an infinite loop. A loop becomes infinite if
the condition or the updation statement is missing from fee loop.
Example :
(i) for(;;)
{}
(ii) for(i=l;i<=10; )
System.out,println(i);
(iii)for(i=l; ;i++)
System. out.println(i); All the above are
examples of an infinite loop.
Q 6. Convert the following segment into an equivalent do loop :
int x,c;
for(x=10,c=20;c>=l
0;c=c-2) x++;
Ans. x = 10,c = 20; /
d
o

{
x++;
c=
c-2;
}
while(c> = 10);
Q 7. Explain the function of each of the following with an
example : (i) break;
Ans. A Java keyword used to resume program execution at the
statement ii following the current statement. If followed by a label,
the program resumes at the labeled statement. Example :
for(int i=l;i<=10;i++)

nit any cone Iwhile is an exar


PL Write the syntax a Syntax of while initialization while(test con
if( i==5) break;
System.out.print(i+ " ");

Output : 12 3 4
(ii) continue;
Ans. A Java keyword used to resume program execution at the end of the cm If followed by a label,
continue resumes execution where the label occurs. Example :
for(int i=l;i<=10;i++)
{
if( i==5 | | i==7 | | i==9) continue;
System.out.print(i+ " ");
}

Output :
1 2 3 4 6 8 10
Q 8. What are entry and exit controlled loops ? Explain. Ans. Entry controlled loops are where
test-condition is evaluated before alk entry into the loop and execute the body. The entry to the loop is
allowed oi
-condition is true.For example: while and for loop are entry controlled loops-Exit controlled loop^
are those where test condition is evaluated after the exe the body of a loop. In this kind of loop the first
entry, to execute the loop is)
ut any condition but the second entry requires the test-condition to be true. While is an example of exit
controlled loop.
Write the syntax of while loop and do..while loop.
Syntax of while loop : initialization while(test condition) {
loop body
updation statement
i
Syntax of do...while loop initialization do

loop body
updation statement
}while(test condition);

Class as a User Defined Types

Q. What is data type?


Ans: Data types are means to identify the type of data and associated operations of handling it.
Q. What is composite (user define) data type? Explain with an example? [2007] [2009]
Ans: A composite datatype is that datatype that are based on fundamental or primitive datatypes. A
'class' is an example of composite datatypes.class Date{  int dd, mm, yy;  public Date()  {    dd=1;   
mm=1;    yy=2005;  }}
Q. What is user defined datatype?
Ans: A user defined datatype is a data type that is not a part of the language and is created by a
programmer.
Q. Can you refer to a class as a user defined (composite) data type? [2009]
Ans: Yes, we can refer to a class not having a main() method as user-defined data type.
Q. What is the difference between primitive data types and composite data types?
Ans: (i) primitive data types are built-in data types. Java provides these data types. User-defined data
types are created by users. (ii) The size of primitive data types are fixed. The size of user-defined data
types are variable. (iii) Primitive data types are available in all parts of Java programs. The availability
of user-defined data types depends upon their scope.
Q. Compare a class as a user defined data type and class as an application?
Ans: In Java, all functionality is enclosed in classes. But in order for a class to be user-defined data
type, it should be act different from that of an application. i.e. it should not include main() method in it.
Although we can create instance of classes containing main method, they should not be referred to as
used-defined data type. Such classes (containing main() method) are more analogues to application than
a data type.

Q. How are private member different from public member of a class.


Ans: Private members of a class are accessible in the member function of the class only, where as
public members are accessible globally.
Q. How are protected members different from public and private members of a class.
Ans: Protected members of a class are accessible in all the classes in the same package and subclass in
the other packages. private members of a class accessible in the member functions in the class only.
Where as public members are accessible globally.
Q. Mention any two attributes required for class declaration. [2008]
Ans: The two attributes for class declaration are: 1. Access Specifier  2. Modifier 3. Class Name
Q . State the two kinds of data types.
Ans. The two data types used in Java language are:
(i) Primitive
ii) Non-primitive or Reference
Primitive data types come as a part of the language. Java provides eight primitive data types, namely
byte, short, int, long, double, float, boolean and char. Non-primitive data types are constructed from
primitive data types. These are classes, arrays etc.
Q . What is the difference between private, protected and public ?
Ans. These are the keywords that determine access privileges to components of a class like data and
functions. Public specifier means that the member'is accessible to all. Private specifier means that the
member is accessible to other members of same class only. Protected specifier means that the member
is accessible to the class to which they belong and any of the sub classes.
Q. Why is class also called composite data type ? Also give an example.
Ans. The class is composed of primitive data types so it is known as composite data
type.
Example :
class Test

int x,y; boolean r;


Since Class Test makes use of different types as its members. It is called composite data type.
Q . What is data type ?
Ans. It is. the means to identify the type of data used and their associated operation.
Q . Which keyword is used to create object ?
Ans. new keyword is used to create object of a class.

Q . Differentiate between Accessor method and Mutator method.


Ans. An accessor method is a method that returns the value of a data-member of the class. Mostly
accessor methods are provided for private members.
A Mutator method is a method that changes the value of a data-member of the class.

Functions

Q. What is Function? Why do we use functions while programs handling?


Ans: A named unit of a group of programs statements. This unit can be invoked from other parts of the
program.
Q. Define Function prototype?
Ans: The function prototype is the first line of the function definition that tells the program about the
type of the value returned by the function and the number and types of arguments.
Q. What is the use of void before function name? [2007]
Ans: void data type specifies an empty set of values and it is used as the return type for functions that
do not return a value. Thus a function that does not return a value is declared as follows. void
<functions name> (parameter list)
Q. Explain Functions/Methods Definitions with syntax?
Ans: A function must be defined before it is used anywhere in the program.[access specifier]
[modifier]return-type function-name (parameter list){  body of the function}[access specifier] can be
either Public, Protected or Private. [modifier] can be one of final, native, synchronize, transient,
volatile. return-type specifies the type of value that the return statement of the function returns. It may
be any valid Java data type. parameter list is comma separated list of variables of a function.
Q. Why main() function so special?
 Ans: The main() function is invoked in the system by default. hence as soon as the command for
execution of the program is used, control directly reaches the main() function.
Q. Explain the function prototype and the signature?
Ans: The function prototype is the first line of the function definitions, that tells the program about the
type of the value returned by the function and the number and type of the arguments. Function
signature basically refers to the number and types of the arguments, it is the part of the prototype.
Q. Explain the function of a return statement? [2006]
Ans: The return statement is useful in two ways. First an immediately exit from the function is caused
as soon as a return statement is encountered and the control back to the main caller. Second use of
return statement is that it is used to send a value to the calling code.
Q. Write advantages of using functions in programs. [2010]
Ans: (i) functions lessen the complexity of programs (ii) functions hide the implementation details (iii)
functions enhance reusability of code
Q. Difference between Actual argument and Formal argument? [2007,2008]
Ans: The parameter that appears in function call statement are called actual argument and The
parameter that appears in function definition are called formal parameter.
Q. What are static members?
Ans: The members(global variables and methods) that are declared with static keyword is called static
members. These members are associated with the class itself rather then individual objects, the static
datamembers and static methods are often referred to as class variables and methods.
Q. What is the use of static in main() methods? [2007]
Ans: (i) They can only call other static methods. (ii) They can only access static data. (iii) They can not
refer to this or super in any way.
Q. What is call by value?   [2005]
Ans: (i) In call by value, the called functions creates its own work copy for the passed parameters and
copies the passed values in it. Any changes that take place remain in the work copy and the original
data remains intact.
Q. Explain the term "passed by reference"? [2007]
Ans: In passed by reference, the called function receives the reference to the passed parameters and
through this reference, it access the original data. Any changes that take place are reflected in the
original data.
Q. Differentiate between call by value and call by reference?
Ans: In call by value, the called functions creates its own work copy for the passed parameters and
copies the passed values in it. Any changes that take place remain in the work copy and the original
data remains intact. In call by reference, the called function receives the reference to the passed
parameters and through this reference, it access the original data. Any changes that take place are
reflected in the original data.
Q. Define an impure functions? [2006]
Ans: Impure Function change the state of the object arguments they have received and then return. The
following functions is the example of an impure function: public static Time increment(Time obj,
double secs){  time.seconds+=secs;  return(Time);}
Q. What is the difference between pure and impure functions? [2009]
Ans: Pure Function: These functions takes objects as an arguments but does not modify the state of the
objects. The result of the pure function is the return value. Impure Function: These functions change
the state of the object arguments they have received.
Q. How are following passed in Java?              [2005]    (i) primitive types    (ii) reference types
Ans: (i) By value,     (ii) By reference.
Q. What does function overloading mean? What is its significance?
Ans: A Function name having several definitions in the same scope that are differentiable by the
number or type of their arguments, is said to be an overloaded function. Function overloading not only
implements polymorphism but also reduce the number of comparisons in a program and there by makes
the programs run faster.
Q. Illustrate the concept of function overloading with the help of an example.  [2006]
Ans:- A function name having several definitions that are differentiable by the numbers or types of
their arguments is known as function overloading. For example following code overloads a function
area to computer areas of circle rectangle and triangle.float area (float radius)            //circle{        return
(3.14 * radius * radius);}float area (float length, float breadth)  //rectangle{    return
(length*breadth);}float area (float side1, float  side2, float side3) //area of triangle{    float s = (side1 +
side2 + side3)/2;    float ar = Math.sqrt(s * (s- side1)*(s-side2) *(s-side3));    return (ar);}
Q. What is ‘this’ keyword? What is its significance? [2009]
Ans: The “this” keyword is used to refer to currently calling objects. The member functions of every
objects have access to a sort of magic keyword name this, which points to the object itself. Thus any
member function can find out the address of the object of which it is a member. The ‘this’ keyword
represents an object that invokes a member function. It stores the address of the object that invoking a
member function and it is an implicit argument to the member function being invoked. The ‘this’
keyword is useful in returning the object of which the function is a member.
Q. What do you mean by recursive function?
Ans: When a method is called inside its own definition the process is known as functions recursion and
this function called recursive function.
Q. What is the difference between Methods and Functions?
Ans: The major difference between methods and functions is that methods called by the reference
variables called objects where as the functions do not having any reference variables.
Q.What do you mean by a function ?
A function is a set of statements enclosed between matching curlv braces to carry a particular
task. The name of the function is given by the user.
Q.What are the advantages of using functions in a program ? The advantages of
using functions in a program are : Functions reduces the complexity of the program by
making the main function very simple.
Functions hide the implementation details . thus only showing the important features and
hiding the background details.
Functions enhances the reusability of the code.
Q. What is call by value ?
The call by value method copies the values of actual parameters into the formal parameters.
Any changes made to the formal parameters in the called function are noted back to the
actual parameters in the calling function.
Example
class Test

void call ( ) {

x=x+10;
Output:
Value of a before calling : 20
Value of a after calling : 20 Here the value of a is copied to variable x. The value of x
changes fr the value of a remains the same as in the original, i.e. 20
Q 4 How are the following passed ?
(1) Primitive types — passed by value
(2) Reference types — passed by reference
Q 5. Define an impure function.
Ans. Impure functions also called modifier functions change the state of: Example :
class Test
{
int a=0;
void change( )

a=a +20;
}
}
Here change function changes the value of the instance variable from 0
Q 6. What is a h function prototype ? Ans. The first line of any function that
includes access specifier, modified of the function, function name and the argument list is
known as function header or function prototype.
Example :
public static void sum (int a, int b)

1
Q 7. What is function signature ?
Ans. The name of the function and the arguments in the parameter list of the function
header is known as function signature.
public static void sum (int a, int b)

Here, Function signature is sum (int a, int b)


Q. What is the feature of static keyword in connection with function ? The
keyword static makes a method as a class function, this means that the method can be called
through class name and not through object of the class.
Q. Define formal and actual parameters. Explain with the help of an example.
[Formal parameters : The list of variables along with their data types given the brackets in
the function prototype are formal parameters.
parameters : The list of variables/values given within brackets at the time »n is called or
invoked are known as actual arguments.
void calc( )

int a=20; change(a);

void changed(int x)

System.out.println( x*2);

‘a’ is an actual parameter , and x is a formal parameter.


Q. What is the difference between call by value method and call by reference
method.
1) In call by value method the value of actual parameter is passed to the
formal parameters. In call by reference method the address or reference
is passed to the formal parameters .
2) In call by value the changes made in formal parameters is not reflected back in actual
parameters. In call by reference the changes made in formal parameters are reflectedd back
in the actual parameters.
3) Primitive data types are passed by value and reference types are passed by reference.
Q. What do you mean by pure function ? State an example also,
The function which does not change the state or modify the state of the object.
class Test
{
int x;
void set(int z)
{

x = z;
}
void change( )
{
System.out. println(x*2); }
Here function change( ) is a pure function, set() is not.
Q 12. How many values a function
returns ? Ans. A function returns
only one value at a time.
Q 13. What do you mean by function overloading? Explain
with the example.
Ans. The logical method of defining various functions in a class by
the same name which are differentiated by their signature is known
as function o^ Function overloading implements polymorphism.
Example :
class Overload
{

void sum(int a) //function 1 with one argument

System.out. println( a*2);

void sum(int a, int b) //function 2 with two arguments

System.out.println( a*b);

void sum(int a,int b,int c) //function 3 with 3 arguments {

System.out.println(a*a+b*b+c*c);

}
}

Q 14. Explain the function of return statement.


Ans. The return statement is used for two purposes : (i) An
immediate exit from function is caused as soon as a return statement
is encountered, (ii) It is used to return a value to the calling function.
Q 15. If a function contains several return statements, how many of
them will be executed ? Ans. Onlv one. he first return statement
encountered.
16.What is the role of void keyword in declaring functions ?
s. void keyword is used as a function return type when the function is
not returning value.
17. What is meant by private visibility of a method ?
is. A method declared private is accessible to other member functions
of the same class only.It is not accessible to other methods of classes
present in the same package or classes defined in other packages.

Constructors

Q. What is constructor?
Ans: A constructor is a member function that automatically called, when the
object is created of that class. It has the same name as that of the class name;
it has no return type and its primary job is to initialise the object to a legal
value for the class.
Q. Why do we need a constructor as a class member?
Ans: Constructor is used create an instance of of a class, This can be also
called creating an object.
Q. Why does a constructor should be defined as public?
Ans: A constructor should be defined in public section of a class, so that its
objects can be created in any function.
Q. Explain default constructor?
Ans: The constructor that accepts no parameter is called the default
constructor. If we do not explicitly define a constructor for a class., then java
creates a default constructor for the class. The default constructor is often
sufficient for simple class but not for sophisticated classes.Example:  class
ant  {    int i;    public static void main()    ant nc=new ant();  }the line new
ant() creates an object and calls the default constructor, without it we have
no method to call to build our objects. once you create a constructor with
argument the default constructor becomes hidden.
Q. Explain the Parameterised constructor?
Ans: If we want to initialise objects with our desired value, we can use
parameters with constructor and initialise the data members based on the
arguments passed to it . Constructor that can take arguments are called
Parameterised constructor.Example:  public class result  {    int per;    int
tot;    public result (int percentage)    {      per=percentage;      tot=0;    }  }
Q. Give a syntax/example of constructor overloading. Define a class, which
accept roll number and marks of a student. Write constructor for the class,
which accepts parameter to initialise the data member. Also take care of the
case where the student has not appeared for the test where just the roll
number is passed as argument.
Ans: class student  {    int roll;    float marks;    student(int r, float
m)                 // constructor with two argument.    {      roll=r;      marks=m;   
}    student(int r)                            // constructor with one argument    {     
roll=r;      marks=0;    }    student()                                  // default
constructor    {      roll=0;      marks=0;    }  }
Q. Mention some characteristics of constructors.
Ans: The special characteristics of constructors are:(i) Constructors should
be declared in the public section of the class. (ii) They are invoked
automatically when an object of the class is created. (iii) They do not have
any return type and cannot return any values. (iv) Like any other function,
they can accept arguments. (v) A class can have more than one constructor.
(vi) Default constructor do not accept parameters. (vii) If no constructor is
present in the class the compiler provides a default constructor.
Q. State the difference between Constructor and Method.  [2005]
Ans: The function has a return type like int. but the constructor has no return
type. The function must be called in programs where as constructor
automatically called when the object of that class is created.
Q. Enter any two variables through constructor parameters and write a
program to swap and print the values.   [2005]
class swap{  int a,b;  swap(int x,int y)  {    a=x;    b=y;  }  public void
main(String args[])  {    int t=a;    a=b;    b=t;    System.out.println("the value
of a and b after swaping : "+a+" "+b);  }}
 Q. What are the types of Constructors used in a class?
Ans: The different types of constructors are as follows:i. Default
Constructors.ii. Parameterized Constructor.iii. Copy Constructors.
Q. Define Copy constructors.
Ans: A copy constructors initializes the instance variables of an object by
copying the initial value of the instant variables from another objects.
e.g.class xyz{  int a,b;  xyz(int x,int z)  {    a=x;    b=y;  }  xyz(xyz p)  {   
a=p.x;    b=p.y;  }}
1. What is the use of Constructor function ?
It is a special function created with the same name as that of a class, has no return type and which
initializes object by assigning values to the data members of the class.

5. What are temporary instances of a class and how it is created ? Give one example also.
It is an anonymous instance that is created to perform one particular job within a new statement.
Temporary instances are created by calling class constructor using new keyword and
explicit method within the statement which performs the job. imple :
new obj.show();

|3. What is the use of the keyword this ?


the "this" keyword represents an object which invokes member of a class. It stores the address of the
current calling object. This is used in another context also, can have local variables and instance
variables with the same name, this can be to resolve such naming conflict as it can be used to refer to
the current object, ;
Class Test {
int x, y;
Test(int x,int y) {
this.x=x; this.y=y;
}

State the difference between Constructor and Method.


(i) A constructor function is defined by the same name as that of a class. A
function is defined by any valid identifier name.
(ii) A constructor has no return type not even void data type. A function contain
either void or a valid return data type.
(ii) A constructor creates an instance of a class. A function contains one or more than one valid
Java statements as its body.
Constructor is called automatically as soon as the object is created. Method must be invoked
explicitly using object of a class.
Q 5. Enter any two variables through constructor parameters and
program to swap and print the values. Ans.
class Test
{
int x,y;
Test( int a , int b) { x=a; y=b; }
void swap( ) {
int z;
System.out.println(“Values before swapping : "+ x + " " + y);
z = x;
x = y;
y = z;

System.out.println(“Values after swapping : "+ x + " " + y);

O 6. What is a default constructor ?

Ans. A Constructor function that the compiler creates for programs by itself there are no user defined
constructors in a class. The default, constructor assigns to all numeric values and null to char and
String values.

Q 7. Define Instance Variable. Give an example of the same. Ans. The variable whose separate
copy is made for all the objects of a class. If there are 20 objects created of a class there will be 20
separate copies of the instance variable Example :
class Test
{
String
name; int
age:
double percent;
}
Here name, age and percent are instance variables of the class Test

Class as the Basis of all Computation

Q. What are keywords? can keywords be used as a identifiers?


Ans: Keywords are the words that convey a special meaning to the language
compiler. No, keywords can never be used as identifiers.

Q. What is an identifier? What is the identifier formatting rule of Java?


OR What are the rules for naming a variable?
Ans: Identifiers are names given to different parts of a program e.g.
variables, functions, classes etc. The identifiers in Java.(i) Can contains
alphabets, digits, dollar sign and underscore.(ii) Must not start with a digit.
(iii) Can not be a Java keywords.(iv) Can have any length and are case-
sensitive.

Q. Why keyword is different from identifiers?


Ans: Keywords are predefined sets of words that have a special meaning for
the Java compiler. Identifiers on the other hand are created by Java
programmers in order to give names to variables, function, classes etc.

Q. State the difference between Token and Identifier.


Ans: The smallest individual unit of a program is known as Token. The
following Tokens are available in Java: Keywords, Identifiers, Literals,
Punctuators or Separators, Operators. Identifiers are names given to different
parts of a program e.g. variables, functions, classes etc. The identifiers in
Java are case sensitive and have some naming rules.

Q. What are literals? How many types of integer literals are available in
Java?
Ans: A literal is sequence of characters used in a program to represent a
constant value. For example 'A' is a literal that represents the value A of type
char, and 17L is a literal that represents the number 17 as value of type long.
Different types of literals available in Java, they are: Integer literal, Float
literal, Boolean literal, Character literal, String literal and null literal.

Q. What is an integer constant? Write integer forming rule of Java.


Ans: Integer constants are whole numbers without any decimal part. The
rule for forming an integer constants is: An integer constant must have at
least one digit and cannot contain a decimal point. It may contains + or -
sign. A number with no sign is interpreted to be positive.

Q. What do you mean by Escape sequence and name few escape


sequences in Java?
Ans: Java have certain nongraphic characters (nongraphic characters are
those characters that can not be typed directly from keyboard e.g. backspace,
tab, carriage return etc.). Those nongraphic character can be represented by
escape sequence. An escape sequence is represented by backslash followed
by one or more character. The few escape sequence characters are: \n for
new line, \t for Horizontal Tab, \v for Vertical Tab, \b for Backspace, \" for
Double Quotes etc.

Q. How many integer constants are allowed in Java? How are they
written?
Ans: Java allows three types of integer constants: Octal (base 8), Decimal
(base 10), and Hexadecimal (base 16). An Octal integer must be started with
a zero '0', a Hexadecimal integer starts with a '0X', all others are treated as
decimal integer constant.

Q. What is meant by a floating constant in Java? How many ways can a


floating constant be represented into?
Ans: Floating constants are real numbers. A floating constant can either be a
fractional or in exponent form.

Q. Differentiate between Integer and Floating type constants.


Ans: Integer constants are the whole numbers (without decimal points). e.g.
1231. Floating point constants are fractional numbers (number with decimal
points). e.g. 14.2356

Q. What is a type or 'Data Type'? How this term is related to


programming?
Ans: A type or datatype represents a set of possible values. When we specify
that a variable has 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.

Q. What is primitive data type? Name its different types.


Ans: Primitive data types are those that are not composed of other data
types. Numeric Integral, Fractional, character and boolean are different
primitive data types.

Q. State the two kind of data types? [2006]


Ans: The two types of data types are: Primitive and non-
primitive/composite/user define data types. The primitive data types are:
byte, short, int, long, float, double, char and Boolean. The non-
primitive/reference data types are: class, array and interface.

Q. Write down the names of three primitive and three non-


primitive/reference data types in Java/BlueJ.
Ans: The primitive data types are: byte, short, int, long, float, double, char
and Boolean. The non-primitive/reference data types are: class, array and
interface.

Q. How many bytes occupied by the following data types: byte, short,
int, long, float, double, char, boolean.
Ans: char-2 byte, byte-1 byte, short-2 bytes, int-4 bytes, long-8 bytes, float-4
bytes, double-8 bytes, boolean-Java reserve 8 bits but only use 1 bit.

Q. What is the range of the following data types: byte, short, int, long,
float, double, char, boolean.
Ans: byte -> -128 to 127short -> -32768 to 32767int -> -231 to 231-1long
->-263 to 263-1float -> -3.4x1038 to 3.4x1038double -> -1.7x10308 to
1.7x10308char -> 0 to 65536boolean - > true or false
Q. What is the largest and smallest value for floating point primitive
data types float?
Ans: The smallest value is -3.4E+38 and largest values is 3.4E+38 of
floating point data type.

Q. What is Token? What are the tokens available in Java?


Ans: The smallest individual unit of  a program is known as Token. The
following Tokens are available in Java:- Keywords, Identifiers, Literals,
Punctuations, Operators.

Q. What do you mean by variables?


Ans: A variable is a named memory location, which holds a data value of a
particular data types. E.g. double p;

Q. What do you mean by variables? What do you mean by dynamic


initialization of a variable?
Ans: A variable is a named memory location, which holds a data value of a
particular data types. When a method or functions is called and the return
value is initialise to a variable is called dynamic initialisation. example
double p=Math.pow(2,3);

Q. What is the function of an operator?


Ans: Operators are special symbols that represent operations that can be
carried out on variables, constants or expressions.

Q. What do you mean by operator and write the name of all operators
given in your textbook.
Ans: The operations are represented by operators and the object of the
operations are referred to as operands. The types of Operators available in
Java are: 1. Arithmetic 2. Increment/Decrement 3. Relational 4. Logical 5.
Shift 6. Bitwise 7. Assignment 8. Conditional 9. [] operator 10. new operator
11. (type) cast Operator 12. () operator. 13. dot operator.

Q. What are arithmetic operators?


Ans: Arithmetical operators are used for various mathematical calculations.
The result of an arithmetical expression is a numerical values. Arithmetical
operators are of following types: Unary and Binary operators.

Q. Write major difference between the unary and binary operators?


Ans: The operators that acts on one operand are referred to as Unary
Operator. There are two Unary operators Unary + operator and Unary -
operator. The operators that acts upon two operands are referred to as Binary
Operator. The Binary Operators are Addition(+), Subtraction (-),
Multiplication (*), Division (/) and Modulus (%).

Q. What is increment operator? What are postfix and prefix increment


operators?
Ans: The '++' operator is called increment operator. The increment operators
add 1 to its operand. These are two types (i) Prefix and (ii) Postfix The
prefix version comes before the operand for e.g. ++a, where as postfix
comes after the operand e.g. a++

Q. Find the value of x after evaluating x += x++ + --x + 4 where x=3


before the evaluation. Explain your answer.
Ans: Result is 13, because x++ is 3, --x is 2 + 4 the answer is 9 add this with
x that is 3 it becomes 12 and due to pre increment of x++ the result becomes
13.

Q. What do you mean by Relational Operators.


Ans: Relational operators are used to determine the relationship between
different operands. These are used in work of compression also. The
relational expression (condition) returns 0 if the relation is false and return 1
if the relation is true. < (less then), > (greater then), <= (less then equals to),
>= (greater then equals to), == (equals to), != (not equals to).

Q. What is Logical operators?


Ans: The logical operators combine the result of or more then two
expressions. The mode of connecting relationship in these expressions refers
as logical and the expressions are called logical expression. The logical
expression returns 1 if the result is true otherwise 0 returns. The logical
operators provided by Java are && Logical AND, || Logical OR, ! Logical
NOT.

Q. What do you man by Assignment Statement or Assignment


Operator?
Ans: Assignment operator is represent by symbol '='. It takes the value on
the right and stores it in the variable on the left side. for example x = y + 30

Q. What do you mean by Shift operators? OR Differentiate between


Shift LEFT and Shift RIGHT operators.
Ans: A Shift operators performs bit manipulation on data by shifting the bits
of its first operand right to left. The shift operators available in Java are:(1)  
>>     shift bits of right by distance. (signed shifting)(2)   <<     shift bits of
left by distance.   (signed shifting)(3)   >>>   shift bits of right by distance 
(unsigned shifting)

Q. Differentiate between Shift LEFT and Shift RIGHT operators.


Ans: Shift LEFT (<<) operatr shifts the bit pattern of the operand towards
left by defined number of bits. Shift RIGHT (>>) operator shifts the bit
pattern of the operand towards right by defined number of bits.e.g. 13>>2  
is 3binary value of 13 is 1101>>2   is 0011 is equivalent to 3. Similarly
LEFT shift (<<) operator is also work.

Q. What do you mean by Bitwise operators?


Ans: The Bitwise operations are performed by Bitwise operator. The Bitwise
operations calculate each bit of their result by comparing the corresponding
bits of the two operands.(a) The AND operator &(b) The OR operator |(c)
The XOR operator ^(d) The compliment operator ~

Q. Illustrate '?' operator with an example?


Ans: It is a conditional operator, that stores a value depending upon a
condition. This operator is also known as ternary operator. The syntax for
this operator is expression1?expression2:expression3 . and the example is 
bonus=sales>15000?250:50;

Q. What is the purpose of new operator?


Ans: We can use new operator to create a new objects or new array. Ex.
myClass obj = new myClass();int arr[] = new int[5];

Q. What do you mean by precedence? Illustrate with the help of


example.
Ans: Precedence is the order in which a program evaluates the operations in
a formula or expression. All operators have precedence value. An operator
with higher precedence value is evaluated first then the operator having
lower precedence value. consider the following example   x = 5 + 4 *6;The
value of this expression is 29 not 54 or 34. Multiplication has been
performed first in this expression.

Q. What is operands?
Ans: An operator acts on different data items/entities called operands.

Q. What do you mean by constant? How you declare a variable as


constant variables.
Ans: The memory variables/locations whose values can not be changed
within the program is called constants. The keyword final makes a variable
as constants.

Q. Which class is used for using different mathematical function in Java


program?
Ans: The class used for different mathematical functions in Java is
java.lang.Math

Q. Write down the equivalent expression for the mathematical


expression   (a) (cos x/tan-1 x)+x    (b) |ex - x|
Ans: (Math.cos(x)/Math.atan(x)) + x      and   Math.abs(Math.exp(x)-x)

Q. What is the difference between these two function Math.ceil() and


Math.rint(), explain with example.
Ans: Math.ceil() this function returns the smallest whole number greater
then or equal to the given number. e.g. Math.ceil(12.85) gives output 13 and
Math.ceil(12.35) also gives output 13. Where as the Math.rint() returns the
roundup nearest integer value. e.g. Math.rint(12.85) gives output 13 but
Math.rint(12.35) gives output 12.
Q. What do you mean by type conversion? What is the difference
between implicit and explicit type conversion explain with example.
Ans: The process of converting one predefined type into another is called
Type Conversion.A implicit type conversion is a conversion performed by
the compiler. The Java compiler converts all operands up to the type of the
largest operand. This is also known as type promotion. e.g. 'c'-32  is
converted to int type. Where as an explicit type conversion is user defined
that forces an expression to be of specific type, this also known as type
casting. e.g. (float)(x+y/2)

Q. What is coercion? How it is implemented?


Ans: Implicit type conversion of an expression is termed as coercion. A
implicit type conversion is a conversion performed by the compiler. The
Java compiler converts all operands up to the type of the largest operand.
This is default type conversion.

Q. What do you mean by type casting? What is the type cast operator?
Ans: The explicit conversion of an operand to a specific type is called type
casting. The operator that converts its operand to a specified type is called
the typecast operator. The typecast operator is ( ) in Java and is used as
(type-to-be-converted-in)

Q. Explain the methods print() and println()?


Ans: A computer program is written to manipulate a given set of data and to
display or print the results. Java supports two output methods that can be
used to send the results to the screen. print() method println() method.The
print() method sends information into a buffer. This buffer is not flushed
until a new line (or end-of-line) character is sent. As a result print() method
prints output on one line.The println() method by contrast takes the
information provided and displays it on a line followed by a line feed.

Q. What is an Expression? Explain its different types.


Ans: An Expression is any statement which is composed of one or more
operands and return a value. It may be combination of operators, variables
and constants. There are three different types of expressions.(1) Constant
Expressions: 8 * 12 /2(2) Integral Expressions: formed by connecting
integer constants x = (a + b)/2(3) Logical Expressions: a > b    or a!=b

Q. Mention three different styles of expressing a comment in a program.


Ans: The two ways of inserting a comments in a program are:  
(i) using //                     single line comments  
(ii) using /*     */           multiple line comments
(iii) using /** */ documentation comments

Q. Differentiate between operator and expression.


Ans: The operations are represented by operators and the object of the
operations are referred to as operands. The expression is any valid
combination of operators, constant and variables.
Q. What is a compound Statement? Give an Example.
Ans: It is a block of code containing more then one executable statement. In
Java the { } is called block and the statements written under {} is called
compound statements or block statement. The { } opening and closing
braces indicates the start and end of a compound statement.
for(int i=1;i<=5;i++)
{
    System.out.println("Hello");
    System.out.println("How");
    System.out.println("are you?");
}

Introduction to Java & BlueJ Environment

Q. Why is Java often termed as a platform?


Ans: Platform is the environment in which programs execute. Instead of
interacting with the Operating System directly, Java programs runs on a
virtual machine provided by Java, therefore Java is often referred to as a
platform also.

Q. What is a bytecode?
Ans: Bytecode is a set of pseudo mechanic language instructions that are
intermediate code obtained on compilation of Java source code and is
understood by the JVM (Java Virtual Machine) and are independent of the
underlying hardware.

Q. What do you understand by JVM?


Ans: JVM or Java Virtual Machine is an abstract machine designed to be
implemented on top of existing processors. It hides the underlying OS from
Java application. Programs written in Java are compiled into Java byte-code,
which is then interpreted by a special java Interpreter for a specific platform.
Actually this Java interpreter is known as Java Virtual Machine (JVM).

Q. What is JDK (Java Development Kit)?


Ans: The Java development kit comes with a collection of tools that are used
for developing and running java programs.

Q. What are Java APIs?


Ans: The Java APIs (Application Program Interface) consist of libraries of
pre-compiled code that programmers can use in their application.

Q. Write the five characteristics of Java/BlueJ?


Ans: 1. Write Once Run Anywhere 2. Light weight code 3. Security 4. Built
in Graphics 5. Object Oriented Language 6. Support Multimedia 7. Platform
Independent. 8. Open Product.

Q. What do you know about BlueJ?


Ans: BlueJ is a Java development environment. It is an IDE (Integrated
Development Environment), which includes an editor a debugger and a
viewer.

Q. How you create, compile and execute a program in Java or BlueJ?


Explain your answer?
Ans: Create: Click on new class button from BlueJ editor, then type the class
name a program icon will be created. double click on it, a program editor
will be open, erase the code and type your program coding. Compile: click
the compile button on the left of the window or right click on the class icon
and select compile from the menu options. Execute: Right click on the class
icon and select new class name option. A dialogue box appears type the
name of the object. A object icon will be created at the bottom. Right click
on the object icon and select the method we want to execute.

Elementary Concepts of Object & Class

Q. What is an Object?
Ans: An Object is an identifiable entity with some characteristics and
behavior. E.g. take a class 'Car'. A car class has characteristics like colour,
gears, power, length etc. now we create the object of that class 'Car' namely
'Indica'.

Q. What is OOP? What are the features/concepts in OOP's?


OR
Name any two OOP'S principles.
Ans: The Object Oriented Programming Paradigm is the latest in the
software development and the most adopted one in the programming
development. The Paradigm means organising principle of a program. It is
an approach to programming. The concepts of OOP's are: (1) Data
Abstraction (2) Data Encapsulation (3) Modularity (4) Inheritance (5)
Polymorphism.

Q. Explain all the Concepts of OOP's?


Ans: Abstraction: It refers to the act of representing essential features
without including the background details or explanation. Encapsulation: It is
the way of combining both data and the function that operates on the data
under a single unit. Inheritance: It is the capability of one class of thing to
inherit properties from another class. Polymorphism: It is the ability for a
message or data to be processed in more than one form.
Modularity: It is the property of a system that has been decomposed into a
set of cohesive and loosely coupled modules.

Q. What are the advantages of OOP's?


Ans: (1) Elimination of redundant coding system and usage of existing
classes through inheritance. (2) Program can be developed by sharing
existing modules. (3) Possibilities of multiple instance of an objects without
any interference. (4) Security of data values from other segment of the
program through data hiding.
Q. What is Class? How Object is related to the Class?
Ans: A Class represent a set of Objects that share common characteristics
and behavior. Objects are instance of a class. The Object represents the
abstraction representation by the class in the real sense.

Q. What is the need of a class in Java?


Ans: Classes in Java are needed to represent real-world entities, which have
data type properties. Classes provide convenient methods for packing
together a group of logical related data items and functions that work on
them. In java the data items are called fields & the functions are called
methods.

Q. What are Methods? How are these related to an Objects?


Ans: A Method is an operation associated to an Object. The behavior of an
Object is represented through associated function, which are called Methods.

Q. Point out the differences between Procedural Programming and


Object Oriented Programming.
Ans: Procedural programming aims more at procedures. The emphasis is a
doing things rather then the data being used. In procedural Programming
parading data are shared among all the functions participating thereby
risking data safety and security. Object Oriented Programming is based on
principles of data hiding, abstraction, inheritance and polymorphism. It
implements programs using classes and objects, In OOP's data and
procedure both given equal importance. Data and functions are encapsulated
to ensure data safety and security.

Q. What is an abstraction?
Ans: An abstraction is a named collection of attributes and behaviors
required to represent an entity or concept for some particular problem
domain.

Q. What is inheritance and how it is useful in Java.


Ans: It is process by which objects of one class acquire the properties of
objects of another class. Inheritance supports the concepts of hierarchical
representation. In OOP the concepts of inheritance provides the idea of
reusability.

Q. What role does polymorphism play as java feature?


Ans: It mean the ability to take more than one form. For example, an
operation, many types of data used in the operation.

Q. What is Data hiding?


Ans: Data Hiding means restricting the accessibility of data associated with
an object in such a way that it can be used only through the member
methods of the object.

Q. What are nested classes?


Ans: It is possible to define a class within another class, such classes are
known as nested classes. A nested class has access to the members including
private members of the class in which it is nested. However the enclosing
class not have access to the members of the nested class.

Q. Differentiate between base and derived class.


Ans: BASE CLASS - A class from which another class inherits (Also called
SUPER CLASS)DERIVED CLASS - A class inheriting properties from
another class. (Also called SUB CLASS)

Conditionals and non-nested loops

Q. What is a statement?
Ans: Statements are the instructions given to the computer to perform any
kind of action, as data movements, making decision or repeating action.
Statements form the smallest executable unit and terminated with semi-
colon.

Q. What are the three constructs that govern statement flow?


Ans: The three constructs that governs statement flow are: Sequence,
Selection and Iteration constructs.

Q. What is a selection/conditional statement? Which selection


statements does Java provides?
Ans: A selection statement is the one that is used to decide which statement
should be execute next. This decision is based upon a test condition. The
selection statements provided by Java are: if-else and switch. The
conditional operator ?: can also be used to take simple decision.

Q. What is an 'if' statement? Explain with an example.


Ans: the 'if' statement helps in selecting one alternative out of the two. The
execution of 'if' statement starts with the evaluation of condition. The 'if'
statement therefore helps the programmer to test for the condition. General
form of 'if' statement.  if(expression) statementif(marks>=80) 
System.out.println("Grade A");

Q. What is the significance of a test-condition in a if statement?


Ans: It is the test condition of an if statement that decides whether the code
associated with the if part or the one associated with the else part should be
executed. The former is executed if the test condition evaluates to true and
the latter works if the condition evaluates to false.

Q. Write one advantage and one disadvantage of using ?: in place of an


if.
Ans: Advantage: It leads to a more compact program. Disadvantage:
Nested ?: becomes difficult to understand or manage.

Q. What do you understand by nested 'if' statements?    


OR
Q. Explain with an example the if-else-if construct.
Ans: A nested 'if' is an statement that has another 'if' in its body or in it's
appearance. It takes the following general form.
if(ch>='A')
{
  if(ch<='Z')
    ++upcase;
  else
    ++other;
}

Q. What is the problem of dangling-else? When does it arise? What is


the default dangling-else matching and how it be overridden?
Ans: The nested if-else statement introduces a source of potential ambiguity
referred to as dangling-else problem. This problem arises when in a nested if
statement, number of if's is more then the number of else clause. The
question then arises, with which if does the additional else clause property
match. For Exampleif(ch>='A')  if(ch<='Z')    ++upcase;else  ++other;The
indentation in the above code fragment indicates that programmer wants the
else to be with the outer if. However Java matches an else with the
preceding unmatched if. One method for over-riding the default dangling-
else matching is to place the last occurring unmatched if in a compound
statement, as it is shown below.if(ch>='A'){  if(ch<='Z')    ++upcase;}else  +
+other;

Q. Compare and contrast IF with ?:


Ans: (i) Compare to IF sequence, ?: offer more concise, clean and compact
code, but it is less obvious as compared to IF. (ii) Another difference is that
the conditional operator ?: produces an expression, and hence a single value
can be assigned, for larger expression If is more flexible. (iii) When ?:
operator is used in its nested form, it becomes complex and difficult to
understand.

Q. What is a switch statement? How is a switch statement executed?


Ans: Switch statement successively tests the value of an expression against a
set of integers or character constants. When a match is found, the statements
associated with the constants are executed. The syntax  switch(expression){  
case constants : statements; break;   case constants : statements; break;}The
expression is evaluated and its values are matched against the value of the
constants specified in the case statements. When a match is found, the
statements sequence associated with that case is executed until the break
statement or the end of switch statement is reached.

Q. What is the significance of break statement in a switch statement?


Ans: In switch statement when a match is found the statement sequence of
that case is executed until a 'break' statement is found or the end of switch is
reached, when a 'break' statement is found program execution jumps to the
line of code following the switch statement.
Q. What is a control variable in a switch case?
Ans: A control variable in switch case is one which guides the control to
jump on a specified case. e.g. switch(x), here 'x' is the control variable.

Q. What is a "fall through"?


Ans: The term "fall through" refers to the way the switch statement executes
its various case sections. Every statement that follows the selected case
section will be executed unless a break statement is encountered.

Q. What is the effect of absence of break in a switch statement?


Ans: Absence of break statement in a switch statement leads to situation
called "fall through" where once a  matching case is found the subsequence
case blocks are executed unconditionally

Q. Write one limitation and one advantage of switch statement?


Ans: Advantage: More efficient in case a value is to be tested against a set of
constants. Disadvantage: switch can test only for quality, so for the rest of
comparisons one needs to use if-else.

Q. Discuss when does an if statement prove more advantageous then


switch statement.
Ans: In the following case if statement proves to be more advantage over
switch statement: (i) When a range of values need to be tested for. (ii) When
relation between multiple variables needs to be tested. (iii) When multiple
conditions need to be tested. (iv) When expressions having a data type other
then integer or character need to be tested.

Q. When does switch statement prove more advantageous over an if


statement?
Ans: The switch statement is more advantageous then the if statement when
the test expression whose data type is either of byte, short, character, integer
or long is to be tested against a set of constants. The reason being that the
switch statement evaluates the expression once whereas the equivalent if
statement evaluates the expression repeatedly.

Q. Explain, with the help of an example, the purpose of default in a


switch statement. [2005]
Ans: The default section is an optional part of the switch statement and the
statement written under default clause are executed when no matching case
is found.
switch(n)
{
  case 1: System.out.println("Sunday"); break;
  case 2: System.out.println("Monday"); break;
  case 3: System.out.println("Tuesday"); break;
  case 4: System.out.println("Wednesday"); break;
  case 5: System.out.println("Thursday"); break;
  case 6: System.out.println("Friday"); break;
  case 7: System.out.println("Saturday"); break;
  default :  System.out.println("Invalid Input");
}

Q. Differentiate between if and switch statements.


Ans: Both are used as a selection statements, there are some difference in
their operations. (i) switch can only test for equality, where as if can
evaluate a relational or logical expression. (ii) it statement can handle ranges
, where as switch case level must be a single value. (iii) if statement can
handle floating point test also, where as the switch case labels must be an
integer or character.

ARRAYS
Q 1. What do you mean by an Array ?
.Ans. An array is a collection of items of same data type that are referred by one name ■but different
index numbers. The values are stored in contiguous memory locations. Each memory location store's
only one value.

Q 2. What do you mean by a subscript ?


Ans. A positive integer enclosed between square brackets is known as subscript index number.
Example : x[5] , here [5] is the subscript

Q 3. What do you mean by subscripted variable ?


Ans. The variable associated with a subscript is know as subscripted variable. Example : a[6] , here a
is a subscripted variable

Q 4. Differentiate between Linear search and Binary search. Ans. (i)


Linear search works on both sorted and unsorted array. Binary search works on
only sorted arrays.
(ii) Linear search reads and compares each element of the array one by one t
match is not found.
Binary search works by dividing the array into two parts out of which one needs to be
searched.
(iii) Linear search becomes inefficient as the size of the array increases.
Binary search is more efficient in case of larger arrays.

Q 5. What is the pre-requisite condition for binary search ? Ans. The binary search works only if
the list is arranged in ascending or descen order.

Q 6. How Oo we declare a single dimensional array ? Ans.


Following are the different ways to declare an array : int a[ 1 = new
intflGi, or
int [ la = new int[10];
or
int a[ ] ; a =
new int[10];

Q 7. Define sorting.
Ans. Sorting of an array means arranging the array elements in a specified order i.i either in ascending
or descending order.
Q 8. What is Selection sort technique ? Ans. Selection sort is a sorting technique where next
smallest(or next largest) element is found in the array and moved to its correct position, e.g. the
smallest element^ should be at first position, second smallest should be at second position and so on.

Q 9. Which element is num[9] of the array num ? Ans.


Element stored at 10m position.

Q 10. Find and correct the errors in the following program segment: int n[ ] = (2,4.6,8.101:
for (int i = System. Ans. The correct int n[ ]= -for (int System.od.:
for (int i = 0; i < = 5; i ++) System.out.println("n[" + i
+ "] = " + n[i ]); Ans. The correct form of the program is
: int n[ ]= { 2,4,6,8,10}; for (int i = 0; i < 5; i ++)
System.out.println("n[" + i + "] = " + n[i ]»:

Q 11. Define searching in an array and what are types of search techniques ? Ans. The process of
finding an element from either an ordered or unordered list of data or array is known as searching.
The following two searching methods are :
(i) Linear search
(ii) Binary search
The method of searching any desired element from an array by comparing each element in
consecutive sequence one by one is known as linear search or sequential search. The method of
searching any desired element from an ordered array in minimum number of comparisons is known as
binary search.

LIBRARY CLASSES
Q 1. What do you mean by a Library ?
Ans. A library is a collection of pre-defined functions or methods which has some meaningful
instructions to the compiler which helps in executing the instructions in a program.

Q 2. What is the difference between <R' and ~R~ ?


Ans. 'R' is a character constant because it is enclosed within single inverted commas where as "R" is
a string constant because it is enclosed with in double inverted commas.

Q 3. What is the difference between String and StringBufTer ?


Ans. A string or sequence of characters created using String class is immutable, where as a string
created using StringBuffer class is mutable, i.e the characters of the string can be modified.
Q 4. What is the difference between length* I and length ? Give an example of each.
Ans. length( ) : This function is used to find the length of the string i.e. number of
characters in the string.
Example : String s="COMPUTER":
int l=s.length( ); will give the answer as 8
length : This is used to find the length of the array.
ICSE Computer Theory Short Question Bank

Example : int a[] = {2,5,6,7,2,7,9};


int 1 = a.length; will return 7

Q 5. Define static variable. Give one example.


Ans. The data members which are declared once for a class and all the objects of this class shares the same copy is
known as class variable. The keyword static is used to make it a class variable. Example :
class Number ' {
static int a;
}
Here a is a class variable.

Q 6. Define static method. Give one example also.


Ans. The method that uses keyword static is known as static method. These functions execute only static data
members. Example :
class check
{
static int a; static void show( )

System.out. println(a);
}

Q 7. What do you mean by a package ? Give three examples.


Ans. A package is a group of similar or related classes together in the form of Java
class libraries in which all related functions and information are stored, which helps
the programmers in their tasks.
Example : java.io, Java .lang, java.util

Q 8. What is the function of import keyword ?


Ans. Import keyword is used to load a package into a program to perform various operations.

Example : import java.io.*; Q 9. What is an

Exception ?
Ans. Exception refers to some contradictory or unusual situation which can be encountered while executing a program.

Q 10. What are the advantages of Exception Handling ? Ans. Advantages of


exception handling are :
(i) It separates error handling code from normal code.
(ii) It clarifies the code and enhances its readability.
(hi) It makes the program clear, robust and fault tolerant.

Q 11. What is a wrapper class ? State example. .


Ans. Wrapper classes convert primitive data types as objects. These are part of Java's
standard library java.lang. /
We can create an object of Integer type from its wrapper class as foil ows : Integer g=new Integer(20);

Q 12. What are the two types of errors ? Ans. Errors are of two
types :
(i) Compile time errors : These are errors resulting out of violation of programming
language's grammar rules.

Page 32 of 48
ICSE Computer Theory Short Question Bank

Example : misspell keywords, missing semi-colon, wrong use of brackets. AH syntax errors are reported during
compilation.
(ii) Run time errors : The errors that occur during runtime because of unexpected
situations. Such errors are handled through exception handling routines of Java.
Examples : Division by zero, array index out of bound, string index out of bound etc.

Q 13. What is the output of the following ?


(i) System.out.println ("four :" + 4 + 2); System.out.println (" four :
"+(2+2)); Ans. four:42 four:4 (ii) String SI = "Hi"; String S2 = "Hi";
String S3 = "there"; String S4 = "HI";
System.out.println(Sl + "equals" + S2 + T + Sl.equals(S2)); System.out.printin (SI + "equals" + S3 + T + SI
.equals(S3)>; ~ , System.out.println(Sl + "equals" + S4 + T + SI .equals(S4)); System.out.println(Sl +
"EquallgnoreCase" +S4 + "'!" +Sl.EqualIgnoreCase(S4));
Ans. Hi equals Hi !true Hi equals there Ifalse Hi
equals HI Ifalse Hi equalsIgnoreCase HI !
true

Q 14. What do the following functions return for : [4] String x = "hello"; String y =
"world";
(i) System.out.prinln(x+y);
(ii) System.out.println(x.lengthO);

) System.out.println(x.charAt(3));
(iv) System.out.println(x.equals(y));
Ans. (i) hello world
(ii) 5
(iii) 1
(iv) false
Q 15. Differentiate between toLowerCaseO and toUpperCaseO methods.
Ans. toLowerCase( ) converts all the upper case characters of the string into 1( case.
The other characters remain unaffected.
toUpperCase( ) converts all the lower case characters of the string into upper The other characters remain
unaffected. Example : String s= "Hello";
System.out.printIn(s.toUpperCase( )); will print HELLO
System.out.printIn(s.toLowerCase( )); will print hello
Q 16. What will be the output for the following program segment ?
String s = new String("abc");
System.out.println(s.toUpperCase()); Ans. ABC

Q 17. Differentiate between compareTo( ) and equals( ) methods.


Ans. equals ( ) checks two string objects for equality. It returns true if the strings equal otherwise it returns false.
compareTo( ) also compares two strings. It returns 0 if both the string are same J returns a positive number is first
string is greater than the second and returns a negative number if first string is smaller than the second.
compareTo( ) checks two strings lexicographically, i.e., according to the dictionary rules. Example :
String x = "hello";
String y = "Hello";
System.out.println(x.equals(y)); will print false
System.out.println(x.compareTo(y)); will print 32

Page 33 of 48
ICSE Computer Theory Short Question Bank

Q. WAP:
Method to accept a string sentence as parameter and extract the words of the sentence and count them. Find
frequency of uppercase, digits in the sentence. Find ascii value of the characters.
Q.WAP:
Method to accept an integer num as parameter and find the number of digits and the sum of the digits
Q. What is the output?
(a) System.out.print(Math.abs (Math.ceil(-4.3));
(b) System.out.println(Math.floor(144.99));
(c) System.out.println(Math.max(Math.min(15, 25), 5));
(d) System.out.println(Math.abs(Math.ceil(-4.5));
(e) System.out.println(Math.rint(3.96));
(f) Math.max (Math.min ( Math.log(Math.pow(Math.sqrt(100),(2+5*4/2))) ,
Math.pow(Math.sqrt(9),3)) ), Math.random()*10));
To print the integer part of a real number and to print the decimal part
(g)
separately.
(h) System.out.print((char) ("Application".lastlndexOf ('O')));
(i) double e = Math.pow(Math.sqrt(25), 3);
(j) System.out.print(e);
(k) Give the output of the following statements :
System.out.println( “Reena”.equals(“reena”));
(l) System.out.println("APTITUDE".compareTo("ATTITUDE")
(m) Find substring of APTITUDE from 4th character to 6th character
(n) Find 2nd character from end of string APTITUDE
(o) Replace all ‘T’ with ‘C’ in APTITUDE
Q.Give the output and the datatype of the following statements :
System.out.println(String(123));
a) System.out.println(Integer.valueOf(“27541415”));
b) Analyse the following program segment and determine how many
times the loop will be executed and what will be the output of the program segment ?
int k=1,i=2;
while (++i < 6) k*=i;
System.out.println(k);
(c) Rewrite if-statement as ternary operator statement
int a = 5;
String w= “”;
if(a % 2 == 0)
w=“Even”;
else
w=“Not Even”;
Ans: String w=(a % 2 == 0)? “Even”: “Not Even”;

(a) What are Bytecode and JVM?


(b) Explain tokens and delimiters with an example?
Q. Name the following:

Page 34 of 48
ICSE Computer Theory Short Question Bank

(i) Name the method that converts a double type value into characters
(ii) Name a class that converts bytes to characters
(iii) Name the package that contains the wrapper classes.
(iv) Name the package that contains the System class.
(v) Name the OOP feature that illustrates the following concept :- There can be two
methods having the same name in Java.
(vi) The conversion of a bigger data type to a smaller data type.
(vii) The operator used to create new object of a class.
iv) The variables whose single copy is made for all the objects of a class.
v) The environment that allows developers to compile, debug and run the program
vi) Object communicate with one another by the use of ?
vii) A Construct that binds one or more primitive data types together to be used a single
Data Type.
viii) indicates that a method has no return type
ix) stores the address of the currently-calling object.
x) the smallest integer data type.
xi) Name the keyword that a class uses to inherit another class
xii) Name the part of the class that allocates memory to an object
xiii) Name the package that contains Scanner class.

(b) Show the working of Bubble Sort of the array elements {5, 1, 12, -5, 16} for each pass
(c) Show the working of Selection Sort of the array elements {5, 1, 12, -5, 16}

Page 35 of 48
ICSE Computer Theory Short Question Bank

NORTH POINT SCHOOL


REVISION WORKSHEET FOR STD X COMPUTER APPLICATION
SECTION-2
Q.1 Define a class called Library with the following description:
Instance variables/data mebers:
int acc_num - stores the accession number of the book
String title - stores the title of the book
String author - stores the name of the author

Page 36 of 48
ICSE Computer Theory Short Question Bank

Member methods:
(i) void input() To input and store the accession number, title and author.
(ii) void compute() To accept the number of days late, calculate and display the fine
charged at the rate of Rs.2 per day.
(iii) void display() To display the details in the following format:
Accession Number Title Author
Write a main method to create an object of the class and call the above member methods.

Q.2 Design a class to overload a function series() as follows:


(i) double series(double n) with one double argument and returns the sum of the series.
Sum=1/1 +1/2+1/3 ……..+1/n
(ii) double series(double a,double n) with two double arguments and returns the sum of
the series.
sum=1/a2+4/a5+7/a8…..+10/a11 to n terms

Q.3 Given below is a hypothetical table showing rates of Income Tax for male citizens
below the age of 65 years:
Taxable Income (TI) in Rs. Income Tax in Rs.
Does not exceed Rs. 1,60,000 Nil
Is greater than Rs. 1,60,000 & less than (TI – 1,60,000) x 10%
or equal to Rs. 5,00,000
Is greater than Rs. 5,00,000 & less than [(TI – 5,00,000) x 20%] + 34,000
or equal to Rs. 8,00,000
Is greater than Rs. 8,00,000 [(TI – 8,00,000) x 30%] + 94,000
Write a program to input the age,gender (male or female) and Taxable income of a
person.
If the age is more than 65 years or the gender is female, display “wrong category”.
If the age is less than or equal to 65 years and the gender is male, compute and
display the Income Tax payable as per the table given above.

Q.4 Using the switch statement, write a menu driven program:


(i) To check and display whether a number input by the user is a composite number or
not (A number is said to be a composite if it has one or more than one factor excluding 1
and the number itself).
Example: 4,6,8,9…..
(ii) To find the smallest digit of an integer that is input.
Sample input : 6524
Sample output : Smallest digit is 2
For an incorrect choice, an appropriate message should be displayed.

Q.5 Write a program to accept a string. Convert the string to uppercase. Count and output
the number of double letter sequences that exist in the string.
Sample Input: “SHE WAS FEEDING THE LITTLE RABBIT WITH AN APPLE”
Sample Output: 4

Page 37 of 48
ICSE Computer Theory Short Question Bank

Q.6 Write a program in Java to input the zone code and salesof 10 salesmen. The zone
code varies from 1 to 4. Find the total sales made in each zone and ouput in the
following format:
ZONE CODE TOTAL SALES IN THE ZONE
1
2
3
4
And also output the following format:
ZONE WITH ZONE CODE SALES
Maximum Sales
Minimum Sales
Mean Sales ---

Q.7 Write a program that reads the following list of cities into an one dimensional array.
The program should accept the name of a city in the list as input and display its position
in the list as the output. The program should be designed to give an error message when a
city is asked whose name is not given in the list. To stop the user input “XXX” is to be
entered as input.. Sort the list of cities in alphabetical/ascending order using the Selection
Sort technique. Sort the list of cities in descending order using the Bubble Sort technique.
Q.8 WAP for Binary Search of an array. Find the location and values of the largest and
smallest elements.

NORTH POINT SCHOOL


ANSWERS TO REVISION WORKSHEET STD X COMPUTER
SECTION-2

1. import java.io.*;

class Library {

int acc-num;

String title;

String author;

Static int days;

Static double fine;

Page 38 of 48
ICSE Computer Theory Short Question Bank

void input(int num, String tit, String auth){

acc_num = num;

title = tit;

author = auth;

Static void compute(int d){

Days=d;

System.out.println(“Enter the number of days (late days)”+ days);

Fine = days*2;

System.out.println(“Fine is = “+fine);

public void display() {

System.out.println(“Accession Number” + “\t” + “Title” + “\t” +


“Author”);

System.out.println(acc_num+ “\t” + title + “\t” + author);

public static void main(String [] args) throws IOExeeption {

BufferedReader br = new BufferedRader(new


InputSteamReader(System.in));

Library lib = new Library();

System.out.println(“Enter the number of days (late days)”);

String a = br,readLine();

int d = Integer.parseInt(a);

lib.compute(d);

Page 39 of 48
ICSE Computer Theory Short Question Bank

2. import java.io.*;

class SeriesOverload {

double series(double n) throws IOException {

System.out.println(“Value of n = “);

double sum = 0;

for(int i = 1; i <=n; i++) {

sum += 1.0/I;

return sum;

double series(double a, double n) throws IOException {

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

System.out.println(“Value of n =” + n);

double sum=0;

int i,j;

for(i=1; i<=n; i=i+3) {

for(j=2; j< n+1; j=j+3) {

sum = sum + i/Math.power(a,j);

return sum;

Page 40 of 48
ICSE Computer Theory Short Question Bank

2. import java.io.*;

class IncomeTax{

public static void main(String [] args) throws IOExeeption {

int age;

int gender;

double income;

double tax;

double p, d, net;

String name, address;

System.out.println(“*******************INCOME
TAX*****************”);

System.out.println(“Enter Age of the Person:”);

BufferedReader br = new BufferedRader(new


InputSteamReader(System.in));

age = Integer.parseInt(br,readLine());

System.out.println(“Enter Income of the Person:”);

Page 41 of 48
ICSE Computer Theory Short Question Bank

income = Double.parseDouble(br,readLine());

System.out.println(“M. Enter M for Male”);

System.out.println(“F. Enter F for Female”);

System.out.println();

System.out.println(“Enter your choice::”);

char choice;

choice = (char)System.in.read();

switch(choice) {

case ‘M’: if(age<=65 && income <= 160000) {

System.out.println(“Tax Amount = Nil”);

else if(age <= 65 and income > 160000 && income <= 500000) {

tax=(income-16000)*0.1;

System.out.println(“Income Tax in Rupees=”+tax);

else if(age <=65 && income > 500000 && income <= 800000) {

tax=(income-500000)*0,2+34000;

System.out.println(“________________________”);

System.out.println(“IncomeTax in Rupees=” +tax);

System.out.println(“________________________”);

Page 42 of 48
ICSE Computer Theory Short Question Bank

else if(age <=65 && income > 800000)

tax=(income-800000)*0.3+64000;

System.out.println(“IncomeTax in Rupees=” +tax);

break;

case ‘F’ : if(age>65) {

System.out.println(“________________________”);

System.out.println(“Wrong Category”);

System.out.println(“________________________”);

break;

2. import java.io.*;

class SwitchCase {

public static void num(String args[]) {

int n=0;d,ctr,choice;

int t;

BufferedReader br = new BufferedReader(new


InputStreamReader(System.in));

Page 43 of 48
ICSE Computer Theory Short Question Bank

System.out.println(“Enter 1 for Checking Composite number:”);

System.out.println(“Enter 2 for Checking the Smallest Digit:”);

System.out.println(“Enter your choice:”);

try {

choice = Integer.parseInt(br.readLine());

catch(Exception e) {

System.out.println(“Input Error!”);

System.exit(0);

System.out.println(“Enter a number =”);

try {

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

catch(Exception e) {

System.out.println(“Input Error!”);

System.exit(0);

Page 44 of 48
ICSE Computer Theory Short Question Bank

d=1;

ctr = 0;

switch(choice) {

case 1:

while(d<=n) {

if(n= =1)

System.out.println(n + “is Not a composite


number”);

System.exit(0);

if(n%d = = 0)

ctr++;

d = d + 1;

if(ctr= =2)

System.out.println(n + “Input Error!”);

(5) import java.io.*;

public class DoubleLetter {

public static void main(String args[]) throws IOException {

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

int x,y;

x=0;

y=0;

int count=0;

String a;

Page 45 of 48
ICSE Computer Theory Short Question Bank

char ch1,ch2;

System.out.println(“Enter String::”);

a = br.readLine();

x = a.length();

if(a == null)

return;

String strU = a.toUpperCase();

System.out.println(“Original String: ”+a);

System.out.println(“String changed to uppercase: ” + strU);

for(y=0;y<x-1;y++) {

ch1 = strU.charAt(y);

ch2 = strU.charAt(y+1);

if((int)ch1 == (int)ch2)

System.out.println(ch1 + “ “ + ch2 + “ is a duplicate sequence”);

6) class Sales {

public static void main(String args[]) throws IOException {

int zonesale[] = new int[4];

boolean cont = false;

char ans = ‘’;

Page 46 of 48
ICSE Computer Theory Short Question Bank

zonesale[1] = zonesale[2] = zonesale[3] =zonesale[4]=0

for(int i =0 ; i < 10; i++) {

BufferedReader br = new BufferedReader(new


InputStreamReader(System.in));

System.out.println(“You are entering Data of


Salesman “ + (i+1):-”);

cont=true;

while(cont)

System.out.println(“ \n \tEnter a Zone Code


(1 – 4) and Sale of Salesman “+(i+1)+” : ”);

zc = Integer.parseInt(br.readLine());

sale[zc] = sale[zc] + Integer.parseInt(br.readLine());

System.out.println(“\tDo you wish to


continue? (Y/N) :”);

ans = (char)br.read();

if(ans = =’n’ || ans = = ‘N’)

cont=false;

max = min = zonesale[0];

maxzone = minzone =0;

for(int i=0;i<4;i++)

System.out.println(“Zone code : “ + (i+1) +”Total


Sales : “ + zonesale[i]);

Page 47 of 48
ICSE Computer Theory Short Question Bank

max = zonesale[i] > max ? zonesale[i]:max;

if(max==zonesale[i])

maxzone = i;

if(zonesale[i] < min)

min = zonesale[i];

minzone = i;

System.out.println(“Maximum Sales :” + max + “ in Zone :


“ + maxzone);

System.out.println(“Minimum Sales :” + min + “ in Zone :


“ + minzone);

Page 48 of 48

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy