Important Java Question For ICSE Class X Board Exam
Important Java Question For ICSE Class X Board Exam
1. What is a bytecode?
Ans: The Java development kit comes with a collection of tools that are used
for developing and running java programs.
Ans: The Java APIs (Application Program Interface) consist of libraries of pre-
compiled code that programmers can use in their application.
1. 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.
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.
Ans: The two types of Java Applications are ‘Internet Applets’ and ‘Stand
alone application’.
Ans: The compiler can only translate a program if the program is syntactically
correct; otherwise the compilation fails and you will not be able to run your
program. Syntax refers to the structure of your program and the rules about
that structure.
The second type of error is a run-time error, so-called because the error does
not appear until you run the program. In Java, run-time errors occur when the
interpreter is running the byte code and something goes wrong.
Ans: Java compiler converts Java source code to byte code. This byte code is
further converted into machine code to make it applicable for the specific
platform by using interpreter.
Ans: Source code is the program developed in Java Language, which is input
to a computer through the keyboard. Compiler converts source code to byte
code for interpretation.
OR
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.
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.
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.
1. What is an abstraction?
Ans: It mean the ability to take more than one form. For example, an
operation, many types of data used in the operation.
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.
Ans: BASE CLASS – A class from which another class inherits (Also called
SUPER CLASS)
Ans: Keywords are the words that convey a special meaning to the language
compiler. No, keywords can never be used as identifiers.
Ans: Identifiers are names given to different parts of a program e.g. variables,
functions, classes etc. The identifiers in Java.
Ans: Keywords are predefine 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.
1. What are literals? How many types of integer literals are available in
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.
1. 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.
Ans: Floating constants are real numbers. A floating constant can either be a
fractional or in exponent form.
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
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.
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.
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.
1. 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.
1. What is the range of the following data types: byte, short, int, long, float,
double, char, boolean.
1. 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.
Ans: The smallest individual unit of a program is known as Token. The
following Tokens are available in Java:- Keywords, Identifiers, Literals,
Punctuations, Operators.
Ans: Operators are special symbols that represent operations that can be
carried out on variables, constants or expressions.
1. 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.
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 (%).
1. 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++
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.
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.
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:
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 3
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 &
Ans: We can use new operator to create a new objects or new array.
x = 5 + 4 *6;
The value of this expression is 29 not 54 or 34. Multiplication has been
performed first in this expression.
1. What is operands?
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.
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.
1. 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.
1. What do you mean by type casting? What is the type cast operator?
[2007]
The println() method by contrast takes the information provided and displays it
on a line followed by a line feed.
for(int i=1;i<=5;i++)
System.out.println(“Hello”);
System.out.println(“How”);
System.out.println(“are you?”);
Use of Constructor
1. What is constructor?
Example:
class ant
int i;
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.
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;
per=percentage;
tot=0;
int roll;
float marks;
student(int r, float m) // constructor with two argument.
roll=r;
marks=m;
roll=r;
marks=0;
roll=0;
marks=0;
}
1. Mention some characteristics of constructors.
(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.
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.
class swap
int a,b;
swap(int x,int y)
a=x;
b=y;
int t=a;
a=b;
b=t;
1. Default Constructors.
2. Parameterized Constructor.
int a.b;
xyz(int x,int z)
a=x;
b=y;
xyz(xyz p)
a=p.x;
b=p.y;
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.
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.
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 a value to the calling code.
Ans: (i) functions lessen the complexity of programs (ii) functions hide the
implementation details (iii) functions enhance reusability of code
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.
Ans: The members that are declared static is called static members. These
members are associated with the class itself rather then individual objects, the
static members and static methods are often referred to as class variables
and methods.
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.
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.
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.
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:
time.seconds+=secs;
return(Time);
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.
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.
return (length*breadth);
float area (float side1, float side2, float side3) //area of triangle
return (ar);
}
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.
Ans: When a method is called inside its own definition the process is known
as functions recursion and this function called recursive function.
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.
Ans: Data types are means to identify the type of data and associated
operations of handling it.
class Date
public Date()
dd=1;
mm=1;
yy=2005;
}
1. What is user define datatype?
Ans: A user defined datatype is a data type that is not a part of the language
and is created by a programmer.
Ans: Yes, we can refer to a class not having a main() method as user-defined
datatype.
Ans: (i) primitive datatypes are built-in datatypes. Java provides these
datatypes. User-defined datatypes are created by users. (ii) The size of
primitive datatypes are fixed. The size of user-defined datatypes are variable.
(iii) Primitive datatypes are available in all parts of Java programs. The
availability of user-defined datatypes depends upon their scope.
Ans: In Java, all functionality is enclosed in classes. But in order for a class to
be user-defined datatype, 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 datatype. Such classes (containing main() method) are more
analogues to application than a datatype.
(d) Default (friendly) access: members with default (friendly) access can be
used within the package where the class is defined.
Ans: Private members of a class are accessible in the member function of the
class only, where as public members are accessible globally.
1. 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.
Ans: The two attributes for class declaration are: 1. Access Specifier 2.
Modifier 3. Class Name
Decision Making
[ICSE Syllabus on this Topic]
1. What is a statement?
Ans: Statements are the instructions given t 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.
Ans: The three constructs that governs statement flow are: Sequence,
Selection and Iteration constructs.
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.
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) statement
if(marks>=80)
System.out.println(“Grade A”);
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.
OR
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;
if(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;
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.
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.
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.
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.
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.
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)
{
default : System.out.println(“Invalid Input”);
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.
Utilization of loops. Fixed number of Iteration. The for Loop, unknown number
of Iteration – while, do-while loop, continue, break. Nested Loops.
1. What is the difference between entry controlled and exit controlled loop?
or
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.
int i=0;
while(i<=10)
i++;
if(i==5)
break;
System.out.println(i);
int i=0;
while(i<=10)
{
i++;
if(i==5)
continue;
System.out.println(i);
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.
Ans: In Java the ‘for’ statement is the most common iterative statement. the
general syntax of the for loop is,
}
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);
1. State one similarity and one difference between while and do-while
loop. [2005]
OR
Ans: Infinite loop is an endless loop whose number of iterations are not fixed.
eg: for(;;)
System.out.println(“java”);
Ans: A Null loop does not contains any statement to repeat where as infinite
loop repeats execution of the statements for endless iterations.
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.
Simple input, output. String, static variables and static methods, packages and
import statements.
Ans: Bye oriented IO reads bytes of data or binary where there is no notation
of datatypes. Character oriented IO on the other hand performs IO which is
specially character oriented. In Java byte oriented IO is performed through
data streams where as character oriented IO is performed through Readers
and Writers.
1. What is an Exception?
Ans: During program development there may be some cases where the
programmer does not have the certainty that this code-fragment is going to
work right, either because it accesses resources that do not exist or it goes
out of range. These types of anomalous situations are generally called
exception and the way to handle then is called exception handling.
Ans: (i) Exception handling separates error handling code from normal code.
(ii) It clarifies the code and enhanced readability. (iii) It stimulates
consequences as the error handling takes place at one place and in one
manner. (iv) It makes for clear, robust, fault tolerant programs.
(iii) Processing exceptions for widely used components that should not
process their own exception.
1. What do you mean by try block? How do you define it, give an example.
Ans: The try block is the one that contains the code that is to be monitored for
the occurrence of an exception. A try block is defined by enclosing the
statements that might possible raise an exception in. For example if the
formatting exception are to be handled while an integer is being read from the
keyboard, then the following try block can be used:
int inData;
try
inData=Integer.parseInt(br.readLine());
1. What do you mean by catch block? How do you define it, give an
example.
Ans: The catch block is the one that contains the code handle an exception. It
must follow the try block. i.e. there should be no statement between the try
and the catch blocks. If the catch block is written for the above try block then
we may do it as follows:
int inData;
try
inData=Integer.parseInt(br.readLine());
catch(NumberFormatException nfEx)
System.out.println(“Input format is incorrect”);
Ans: The finally block is one of the exception handling blocks. The code
written in this block is always executed irrespective of whether an exception
was reported or not, or even if it was handled successfully or not. The purpose
of this block is to do cleaning up tasks, e.g. closing files etc.
Ans: EOFException: Signals that an and of the file or end of the stream has
been reached unexpectedly during input.
Ans: A data type starts with lowercase letter and wrapper class starts with
uppercase letter.
1. Define String?
Ans: A string is a set of two or more then two characters, a set of characters
with the digit or a statement written with in double quotes. e.g. “Happy New
Year”, “Computer Application” etc.
Ans: The String object of Java is immutable, i.e. once created they can not be
changed. if any change occurs in a String object, then original object string
remains unchanged and a new String is created with the changed String.
StringBuffer objects are mutable, on the other hand. That is these objects can
be manipulated and modified as desired.
Ans: The purpose and syntax of the following string functions are:
toLowerCase(): This function converts all the characters of the string in lower
case.
for example:
String n=”AMITABH”;
n=n.toLowerCase();
System.out.println(n);
toUpperCase(): This function converts all the characters of the string in upper
case.
for example:
String n=”amitabh”;
n=n.toUpperCase();
System.out.println(n);
replace(): This function replace all the occurrence of a characters with another
one.
String n=”DAD”;
n=n.replace(‘D’,’G’);
System.out.println(n);
trim(): This function is used to remove all the white spaces at the beginning
and end of string.
String n=”AMIT “;
n=n.trim();
System.out.println(n);
equals(): This function is used to compare two string and give true or false if
they are equal.
String s1=”AMIT”;
String s2=”amit”;
System.out.print(s1.equals(s2));
length(): This function return the length characters present in the string.
String s=”AMITABH”;
System.out.print(s.length());
String s=”AMITABH”;
System.out.print(s.charAt(2));
String s1=”AMITABH “;
String s2=”BANERJEE”
System.out.print(s1.concat(s2));
substring(): This function returns the substring starting from the nth character
of the string.
String s=”AMITABH”;
System.out.print(s.substringt(3));
This function also returns the substring starting from the mth character upto
the nth character without including the nth character of the string.
String s=”AMITABH”;
System.out.print(s.substringt(2,4));
indexOf(): This function returns the position of the first occurrence a character
in the string.
String s=”AMITABH”;
System.out.print(s.indexOf(‘A’));
This function also returns the position of the character from the nth position of
the string.
String s=”AMITABH”;
System.out.print(s.indexOf(‘A’,2));
compareTo(): This function returns negative if first string is less then second
string, positive if greater and zero if equals.
String s1=”AMIT”;
String s2=”SUMIT”
System.out.print(s1.compareTo(s2));
Ans: Both the functions is used to compare strings, the difference being that
equals() distinguishes between upper case and lower case version of a
character, where as equalsIgnoreCase() carries out comparison ignoring the
case of characters.
Ans: Both the functions is used to comparing two strings, the difference being
that (i) equals() method only comparing two string and gives they are equal or
not, where as compareTo() methods also gives whether first string is greater
or smaller then second one. (ii) equals() methods returns a boolean value,
where as compareTo() methods return integer value.
Ans: The given two string method’s change the case of the current string. The
toLowerCase() method change the current string object to its equivalent
Lower Case, where as toUpperCase() method change the current string
object to its equivalent Upper Case.
1. What is the difference between the length() and capacity() string
function.
Ans: The function length() returns the number of character contains in a string.
Where as capacity() returns the maximum number of character that can be
stored in a string objects.
Ans: The members that are declared static are called static members. These
members are associate with the class it self rather than individual objects.
Ans: Static variables are used when we want to have a variable common to all
instances of a class.
Ans: Java contains extensive library of pre-written classes we can use in our
programs. These classes are divided into groups called packages. Various
packages in Java are:
java.applet, java.awt, java.io, java.lang, java.new, java.util etc.
Ans: Java API packages provide a large number of class grouped into
different packages according to functionality.
Ans: The packages which are organised in hierarchical structure are referred
as system packages.
Ans: To import a member of package into the current file, put an import
statement at the beginning of the file before any class definitions but after the
package statement, if there is one .
(v) Can be accessed using either the class name or name of any instance of
the class. (i) Declare without the static keyword.
(ii) Exist at instance level i.e. can not be used if there are no instance of class
exist in memory.
(v) Can be accessed using the name of the instance only to which they
belong.
Ans: A data member that is created for every objects of the class.
}
1. State the difference between == operator and equals() method. [2008]
Ans: ==: 1. It is a relational operator. 2. it tests the value on the right side with
value on the left side.
Encapsulation
private, public, scope and visibility rules. packages and package level access.
Ans: The wrapping up to data and methods into a single units (called class) is
known as encapsulation. For example an engine of car or any vehicle
contains many small parts, which enables the entire machinery system to
work. Encapsulation property hides the inner working of objects from the real
world.
Ans: A java program contains many classes. But one class in a Java program
contains the main() method. This class is called initial class.
Ans: A data member that is declared once for a class. All objects of that class
type, share these data members, as there is single copy of them available in
memory. Keyword ‘Static’ in the variable declaration makes a class variable.
Ans: A data member that is created for every objects of the class.
Ans: Visibility is a related term which refers to whether one can use a variable
from a given place in the program.
Ans: (i) Data declared at the class level can be used by all methods in the
class.
(ii) Data declared within a method can be used only in the method.
(iv) Variable that are declared in block i.e., local variable are available to every
method inside of the block.
(v) Variable declared in interior blocks are not available outside of that block.
(vi) Variable declared in exterior blocks are visible to the interior blocks.
(b) PRIVATE: It means that only the methods in the same class are permitted
to use this method.
(c) PROTECTED: It means that methods in this class and methods in any
subclass may access this method.
Ans: Member variables are also known as Instance variables. These member
variables are used to store value in the class. It may be public, private and
protected, where private and protected members remains hidden from outside
world and there by support data.
Ans: PRIVATE visibility of a Method means that only the methods in the same
class are permitted to use this method.
Arrays
Array and their usage, sorting algorithm – selection sort and bubble sort,
search in sorted array. The class objects compatible with all the class.
(i) Single Dimensional Arrays: A list of items can be given one variable name
using only one subscript and such a variable is called a single subscripted
variable or a one or single dimensional array.
(ii) Multi Dimensional Arrays: This type of arrays are actually arrays of arrays.
Ans: The Advantages or Arrays are: (i) Easy to Specify. (ii) Free from run-time
overload. (iii) Random access of elements. (iv) Fast Sequential Access.
Ans: Array can be initialized at the time of declaration by providing the value
list at the same time.
Ans: The subscripts other than 0 to n-1 for an array having n elements are
called out-of-bounds subscripts.
Ans: This search technique searches the given ITEM in minimum possible
compression. The Binary search requires the array must be sorted in any
order. The search ITEM is compared with middle element of the array. If the
ITEM is more then the middle element later part of the arrays becomes the
new array segment. The same process is repeated until either the ITEM is
found or the array segment is reduce to single element.
Ans: In linear search each elements of the array is compared with the given
item to be searched for one by one while binary search searches for the given
item in a sorted array. The search segment reduces to half at every
successive stage.
Ans: For Binary Search The List must be sorted, lower bound upper bound
and the sort order of the list must be known.
Ans: The Linear search compares the search item with each element of the
array, one by one. If the search item happens to be in the beginning of the
array, the compressions are low, however if the element to be searched for is
one of the last elements of the array, this search technique proves the worst
as so many comparisons take place. The Binary search on the other hand,
tries to locate the search item in minimum possible comparisons, provided the
array is sorted. This technique proves efficient in nearly all the cases.
Ans: In bubble sort the adjoining values are compared and exchanged if they
are not in proper order. This process is repeated until the entire array is
sorted.
Ans: 10th element. Because the first index number/subscript value of an array
is 0. So 9th element is treated as the 10th element in an array.
Operations on File
Stream – byte and character stream, files and operation on files. token and
String Tokenizer and stream Tokenizer classes.
1. What is File?
Ans: A file is a means of making data persistent. It is a set of bytes that is
stored on a storage device and can be referred to by a name.
Ans: All programs need to handle data flow to or from a file, a pipe or an I/O
device. Stream are object representation of this flowing data and are used by
java to carry out data interchanged in a program.
Ans: InputStream class provides the basis for classes used to read binary
data from a file, a pipe or an input device.
Ans: Reader class provides the basis for classes used to read character data
from a file or an input device.
Ans: OutputStream class provides the basis for classes used to write binary
data to a file, a pipe or an output device.
Ans: Writer class provides the basis for classes used to write character data to
a file, a pipe or an output device.
1. Name the most commonly used classes for handling Byte oriented IO.
Ans: Classes for byte I/O are DataInputStream and DataOutputStream.
Ans: When an existing file is to be opened for writing all the data of the file is
truncated unless it is opened in the append mode using the following syntax:
Ans: A buffer represent a section of memory used as a staging area for input
or output data? Buffered I/O is an input or output operation that uses
temporary storage called a buffer to hold data before it is transferred from the
source to the destination.
Ans: An input buffer is used for sending a large chunk of data from a stream.
the buffer is then accessed as needed and when emptied another chunk of
data is read from the stream into the buffer. An output buffer is used to store
up data to be written to a stream. Once the buffer is full, the data is sent to the
stream all at once and the buffer is emptied to receive more data.
Ans: A Stream Tokenizer takes an input stream and parses it into tokens,
allowing the tokens to be read one at a time. When reading an input string
supplied by a user we like to be able to analyze it token by token. To isolate
such tokens, we use the String Tokenizer class. We can also use the string
Tokenizer to process input from a file line by line.
Ans: In text file data are stored as per a specific character encoding scheme.
In binary files, data are stored in the form of bytes that are machine readable
form.
Q. The following program is supposed to check the given number is prime or not. Some part
of the program is replaced by ______, with the numbering 1 to 5, fill this part so that program
works correctly.
class checkPrime
{
public static void main(String args[])
{
int i, f=0;
int n = Integer.parseInt(args[0]);
for(i=__1__; __2__; i++)
{
if(__3__==0)
{
f=__4__;
break;
}
}
if(f==__5__)
System.out.print(“The given no. “+n+” is a prime number”);
else
System.out.print(“The given no. “+n+” is not a prime number”);
}
}
Ans: (1) 2 (2) i<n or i<=n/2 (3) n%i (4) 1 or f++ (5) 0
Q. The following program is supposed to print the following pattern. Some part of the
program is replaced by ___n____ where n is 1 to 5, fill this part so that program works
correctly.
5
45
345
2345
12345
class ques
{
public static void main(String args[])
{
for(__1__; __2__; i–)
{
for(__3__; __4__; __5__)
System.out.print(j);
System.out.println();
}
}
}
Ans: (1) int i=5 (2) i>=1 (3) int j=i (4) j<=5 (5) j++
1. 6
2. n
3. n–
4. a[j+1]
5. a[j]
Q. The following function is a part of a class. It computes x raised to the power n. Here x is
the base and n is the power. Some part is replaced by ______, with numbering 1 to 5, fill this
part by expressions or statements so that program works correctly. [10]
double integralPower(double x, int n)
{
int inverse = 0;
double result = 1.0;
if (n == 0)
return ___1___;
else if (n < 0)
{
inverse = 1;
n = ___2___;
}
for(int i=1; ___3___; i++)
{
double temp =___4___;
result = ___5___;
}
return result;
}
1 -> 1
2 -> Math.abs(n)
3 -> i<=n
4 -> (inverse==0)?x:1/x
5 -> result*temp
Q. The following function is part of a class, which finds the lowest common devisor (except 1)
of two given numbers. Some part is replaced by _____, with numbering 1 to 5, fill this part by
expressions or statements so that program works correctly. [10]
public class lcd
{
public int main(int num1,int num2)
{
int small, res, found;
small = ___1___;
res = 2;
found = 0;
while(found==0 && ___2___)
{
if(num1%res==0 && num2%res==0)
___3___;
else
___4___;
}
if(found==0)
return(___5___);
else
return(res);
}
}
1 -> (num1>num2)?num2:num1
2 -> res<=small
3 -> found=1
4 -> res++
5 -> num1*num2
Q. The public function find() has been written to do a binary search for the integer m in the
sorted integer array data. The array is sorted in ascending order. If m is present in data then
it returns 1 else 0. Some part is replaced by ______, with numbering 1 to 5, fill this part by
expressions or statements so that program works correctly. [10]
int find(int m, int data[], int size)
{
/* data is a sorted array of integers arranged in ascending order. size gives the number of
elements in the array. m is the integer which we are trying to search in the array.*/
int found = 0;
int j = 0, k = ___1___;
int i=(j+k)/2;
if(___2___)
{
while(___3___)
{
i=(j+k)/2;
if(m==data[i])
{
___4___; break;
}
else
{
if(___5___) j=i+1;
else k=i-1;
}
}
}
return(found);
}
1 -> size-1
2 -> data[(j+k)/2]>m
3 -> j<=k && found==0
4 -> found=1
5 -> data[I]<m
Ans: The output of the method is 5 8 , the method interchange the value of two variables.
The name of the method must be swap() instead of x() so that it’s name is most
understandable.
Q. Given the following declarations:
String a=”abc”;
String s=a;
String t;
What is the value of the following expression (assume that there is no error)?
a) s.length();
b) 1+a;
c) “Tomorrow”.indexOf(‘r’);
d) “Tomorrow”.substring(2,4);
e) (a.length()+a).startsWith(“a”);
f) a.substring(1,3).equals(“bc”);
Sandeep
Sandeep
(i) Math.exp(Math.abs(2*x-4*x)) (ii) Math.sqrt(Math.sin(a)+Math.atan(a)-
Math.exp(2*x))
Q. Find the output of the following questions. Give the dry run or working. In one line say
what is being computed by the function. [10]
(i) j = 4 k = 4
(ii) 9 4 1 16 0
(iii) The function move the lowest number to the end of the array. The name of the technique
used is called bubble sort.
1 3 6 10
The function “output()” is called recursive function. While writing this type of function the
function definition part must contains a condition to stop the process.
6
The above function print sum of all even numbers from 0 to 5.
Q. The following public function is part of some class. Assume n is always positive. Answer
the given questions. Give the dry run/working.
public static int unknown(int n)
{
int i,k;
if(n%2==0)
{ i=n/2; k=1; }
else
{ k=n; n–; i=n/2; }
while(i>0)
{ k=k*i*n; i–; n–; }
return(k);
}
i. What value will be returned by the expression unknown(7) [4]
ii. What value will be returned by the expression unknown(6)[4]
iii. In one line say what is being computed by the function [2]
(I) 5040
(II) 720
(III) The above function calculates the Factorial of a given number.
Q. The following public function is part of some class. Assume n is always positive. Answer
the given questions. Give the dry run/working. [4+4+2]
int someFn(int a, int b)
{
int ans,sm,la;
if(a<b) { sm=a; la=b; }
else { sm=b; la=a; }
ans=la;
while(ans%sm!=0)
ans+=la;
return(ans);
}
What will be the output of the following function for?
(i) someFn(7,5) (ii) someFn(6,8)
(iii) In one line state what the function someFn() doing?
(i) 35
(ii) 24
(iii) The above functions find the LCM of two given value.
Q. Find out the output of each of the following programs. Dry run or working is necessary, (if
possible).
A
MA
IMA
TIMA
120
620.0
252.0
78.0
14.0
0.0
10 50 30
10 20 10
true
30
50 50 30
10 20 50
400
200
76
1100
1101
1
4
public class q6 [1]
{
public static void sampleMethod()
{
System.out.println(13 & 25);
}
}
20
10 10 30
10 20 10
L
OL
YOL
OYOL
LOYOL
ALOYOL
120
104
116
136
136
100
10 50 30
10 20 30
EBJECT
43
90
53
180
public class xyz [4]
{
public static void main()
{
int a,b,w,x,y,z;
a=10;b=8;
w = ++a – b– ;
System.out.println(w);
a=10;b=8;
x = a % b++;
System.out.println(x);
a=10;b=8;
a*=b+5;
System.out.println(a);
z=69>>>2;
System.out.println(z);
}
}
3
2
130
17
not equal
a
Q3. Write the output after each pass (only five pass), if we apply insertion sort algorithm in
ascending order on following numbers: 2,8,1,9,4,3 [5]
Pass I 2 8 1 9 4 3
Pass II 1 2 8 9 4 3
Pass III 1 2 8 9 4 3
Pass IV 1 2 4 8 9 3
Pass V 1 2 3 4 8 9
Q4. Write the output after each pass (only five pass), if we apply bubble sort algorithm in
descending order on following numbers: 2,8,1,9,4,3 [5]
Pass I 8 2 9 4 3 1
Pass II 8 9 4 3 2 1
Pass III 9 8 4 3 2 1
Pass IV 9 8 4 3 2 1
Pass V 9 8 4 3 2 1
Q3. Write the output after each pass (only five pass), if we apply insertion sort algorithm in
ascending order on following numbers: 2,8,1,9,4,3 [5]
Pass I 2 8 1 9 4 3
Pass II 1 2 8 9 4 3
Pass III 1 2 8 9 4 3
Pass IV 1 2 4 8 9 3
Pass V 1 2 3 4 8 9
Q6. Write the output after each pass (only five pass), if we apply selection sort algorithm in
descending order on following numbers 2,8,1,9,4,3 [5]
Pass I 9 8 1 2 4 3
Pass II 9 8 1 2 4 3
Pass III 9 8 4 2 1 3
Pass IV 9 8 4 3 1 2
Pass V 9 8 4 3 2 1
Q6. Write the output after each pass (only five pass), if we apply insertion sort algorithm in
descending order on following numbers: 2,8,1,9,4,3 [5]
Pass I 8 2 1 9 4 3
Pass II 8 2 1 9 4 3
Pass III 9 8 2 1 4 3
Pass IV 9 8 4 2 1 3
Pass V 9 8 4 3 2 1
Q. If m=5 and n=2 output the values of m and n after execution in (i) and (ii). [ICSE
2005]
(i) m -= n;
(ii) n = m + m/n;
Ans: (i) the value of m is 3 and n is 2 (ii) The value of m is 5 and n is 7
(i) 5 * ++x
(ii) 5 * x++
char c = ‘A’;
short m = 26;
int n = c + m;
System.out.println(n);
Ans: output is 91, because adding ‘char’ with integer data type ‘short’, the least data type
‘char’ converted to integer ‘short’. i.e. ‘A’ becomes 65, so 65+26 is 91.
String y = “world”;
(i) System.out.println((x + y);
(ii) System.out.println((x.length());
(iii) System.out.println((x.charAt(3));
(iv) System.out.println((x.equals(y));
1. A Class is a set of objects that have a common structure and common behavior.
12. The number and type of arguments of a functions are known as function signature.
The first line of functions definition that tells about the type of return value along with
13.
number and type of arguments is called function prototype.
15. Character set is set of valid characters that a language can recognize.
19. Literal are data items that never change their value during a program run.
20. The region of program within which a variable is accessible is called its Scope
22. Static variables are created once for entire class and are shared by all the object.
34. A Member functions with the same name as its class is called constructor
If a local variables is having the same name as that of global class elements then
47.
it Hides the global variables.
52. Total size of array A having 25 elements of char type is 50 bytes
54. The data type of array elements is known as the base type of the array.
55. In Java, array indices start is known as the 0 and are uptil size 1
57. Sorting of an array means arranging the array elements in a specified order.
72. The entire set of Date and code of an object can made a user defined data.
73. Insulation of the data from direct access by the program is called data hiding.
Modularity refers to the source code for an object which can be written and
76.
maintained independently.
81. Data is encapsulated is a class by placing data fields data fields the body of class
definition.
The real world objects are implemented in software form by representing their state
82.
through variables or data items called Member variables.
84. Character set is set of valid characters that a language can recognize.
88. Literals are data items that never change their value during a program run.
89. The region of program within which a variables is accessible is called its Scope.
91. Static variables are created once for entire class and are shared by all the objects.
100
A private or protected constructor is not available to the Non-Member functions.
.
101
The default constructor Initialize the data members by any dummy value.
.
102
Declaring a constructor with arguments Hides the default constructor.
.
103
A Member function with the same name as its class is called constructors.
.
104
Constructor function is defined with Public access specifier.
.
105
A class can have multiple constructors for various situations.
.
106
Constructor that can take arguments are called Parameterized constructor.
.
107
A constructor that accepts no parameter is called the Default constructors.
.
108
The constructor can be used to perform Initialization.
.
109
An array is simply a sequence of either Objects or primitives.
.
110
Array elements of primitive types are automatically initialized to Empty/Null.
.
111
A private constructor allow objects creation only inside Member functions.
.
112
A constructor functions has No return type.
.
113
A class Encapsulates data methods and functionality.
.
114
Java resolves duplicates variables name to most Local scope variable.
.
115
Through Public access specifier a class makes its elements visible.
.
116 If a local variable is having the same name as that of global class elements then
. it Hides the global variable.
117
Region within which a variable/pieces-of-code is accessible scope.
.
118
Variable declared inside a method or block local.
.
119
Class variable which is available to the entire class global variable.
.
120
In Java for an array having N elements legal subscripts are 0 to N-1.
.
121
Total size of array A having 25 elements of char type is 50 bytes.
.
122
Total size of array B [10] [5] of int type is 200 bytes.
.
123
The data type of array elements is known as the base type of the array.
.
124
In java array indices start from 0 and are uptill sixe 1.
.
125
Two dimensional arrays are stored in memory in a row-column matrix
.
126
Sorting of an array means arranging the array elements in a specified order.
.
127
(i) Binary IO is performed using Input and output streams.
.
128
(ii) Streams Tokenizer is used to parse Streams into tokens.
.
129
(iii) Data that need to be stored Permanently must
.
[3] 1 & 0 is
[6] Function not returning any value has return type as:
(b) formal
(a) actual parameter (c) call parameter (d) all of the above
parameters
[10] The function call in which the data in actual parameters gets changed is known as
[11] The function call in which the data in actual parameters gets changed is known as.
[12] The function that changes the state of its parameters is called.
(b) impure
(a) pure function (c) change function (d) none of the above
function
(a) it help cope up (b) it makes (c) it hides the (d) it offers
complexity in subprogram implementation mathematical solution
programs reusable details of problems