Download as pdf or txt
Download as pdf or txt
You are on page 1of 19

CH 1: INTRODUCTION TO OBJECT ORIENTED PROGRAMMING CONCEPTS

1. What are the two types of programming languages?


Ans. Low level languages and high level languages.
2. What are the programming language generations?
Ans. First generation language (machine language), second generation language( assembly language),
third generation language(BASIC, COBOL, C),fourth generation language (SQL, WAVE) and the fifth
generation language (Prolog, Mercury).
3. What do you mean by programming paradigm?
Ans. It is an approach to solve a given problem by writing a set a instructions in a programming
language. It refers to the organizing principles of a program.
4. What are the different programming paradigms?
Ans: Procedural or modular programming and Object oriented Programming.
5. What is Object Oriented Programming?
Ans: The object oriented programming approach focuses a problem in terms of classes and objects. The
OOP determines the classes and objects needed for the solution of a problem and provides a full set of
operations for each class.
6. State the four characteristics/principles of Object Oriented Programming.
Ans. Encapsulation, Abstraction, Polymorphism and Inheritance
7. State three differences between Procedure Oriented Language and Object Oriented
Languages.
Procedure Oriented Programming Language Object Oriented Programming Language

A large program is divided into smaller segments or A program is represented as an object.


procedures.
More importance is given to the function rather More importance is given to the data rather
than the data. than the function.
It follows top down approach. It follows bottom up approach.
8. What is an abstraction?
Ans: The act of representing the essential features without including the background details or
explanation. E.g. in a switchboard we press the switches according to our requirements without knowing
the circuitry.
9. What is encapsulation?
Ans:The wrapping up of data and functions into a single unit called a class in known as encapsulation.
E.g In a medicine capsule all the constituents are encapsulated inside the capsule. Doctor administers
the intake of the entire capsule.
10. What is inheritance and how it is useful in Java. Give examples.
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.
e.g. A class CAR inherits some property from the class Automobiles, which in turn inherits properties
from Vehicle class. The capability to pass down properties and so allows us to describe things
efficiently.
11. What role does polymorphism play as java feature?
Ans: It means the ability for a message or data to take more than one form. For example, an operation,
many types of data used in the operation.
E.g. a child behaves like a student in school, customer in a shopping mall, passenger in a bus and like a
son/daughter at home. Same person behave differently in various circumstances

Ch 2: INTRODUCTION TO JAVA
1. What was Java originally known as? Who developed Java?
Ans. Java was originally known as OAK. It was developed by James Gosling .
2. What are the characteristics of Java?
Ans: The characteristics of Java as follows:
i) It is an object oriented language, simple and robust.
ii) Java program is both compiled and interpreted.
iii) Write once run anywhere (WORA). The java programs are written once, but can be run on different
platform without making changes.
iv)Has enhanced security features.
v)Platform independent.
3. Name two types of Java programs.
Ans. Application and Applet
4. Explain the two types of Java programs.
Ans: Two types of Java programs are Applets and Stand alone applications. i. Applets – small programs
that are embedded in web pages and are run on the viewer‟s machine by Java capable sc owsers.
Used for games and simulation programs. ii. Standalone application- includes the software
applications that do not require low level operating system or hardware access. This includes most
desktop applications like word processors and spreadsheets
5. What is Java API?
Ans. An application programming interface (API), in the context of Java, is a collection of prewritten
packages, classes, and interfaces with their respective methods, fields and constructors.
6. Define the term byte code.
Ans. Java compiler converts Java source code into an intermediate binary code called Bytecode.
Bytecode can't be executed directly on the processor. It needs to be converted into Machine Code
first.
7. What is the difference between source code and object code?
Ans.
Source Code Object Code
It is a set of statements in a High-Level It is a set of statements in Machine
programming language. Language.
It is understood by human/programmer. It is understood by the processor.
8. How does ordinary compilation take place?
Ans. The process of converting the source code into machine code is called compilation. The
compilation produces the machine code. For different platforms different machine codes are produce.
e.g Windows compiler produces an object code that run in Windows computer only.
9. Briefly explain the compilation process of Java source code.
Ans. Compilation in java: i. Java programs are written in “.java” files and are compiled by the compiler
to produce the bytecode (.class file) ii. The JVM is a virtual machine which reads the byte code and
interprets into machine code(object code)
10. What is Java Virtual Machine (JVM)?
Ans. Java Virtual Machine (JVM) is a software that takes Bytecode as input, converts it into Machine
code of the specific platform it is running on and executes it. JVM is platform specific, each platform
has its own JVM.
11. State the difference between Applet and Application.
Ans. The fundamental difference between the two Java programs is that an application program is
designed to run on a stand-alone machine whereas an applet is a web-version of an application which
is used to run a program on a web browser
12. What is package?
A java package is a group of similar types of classes, interfaces and sub-packages.
Package in java can be categorized in two form, built-in package and user-defined package.
There are many built-in packages such as java.lang, Java.io, java.util etc.

13. Name a package that is invoked by default.


java.lang
14. Why do we use main( )?
Ans. In a Java standalone program the execution begins from the main( ). The main( ) is the entry point
in Java and all other functions are called from this method.

CH 3: ELEMENTARY CONCEPT OF OBJECTS AND CLASSES


1. Define the terms:
I. Object- an object is an identifiable entity with some characteristics/properties/attribute, state
and behavior.
II. Attributes- the properties defining an object are termed as attributes or characteristics of an
object
III. State – the state of an object includes all the static properties plus the current values of these
properties.
IV. Class- a class is a blueprint defining the structure( characteristics and behavior) of objects on
which actual objects are created.
2. What is an Object? Give five examples of real world objects.
Ans: An object is an entity having a specific identity, specific characteristics and specific behavior.
Examples — car, bottle, mobile phone, computer, student.
3. How will you define a software object?
Ans: A software object replaces the characteristics and behaviours of a real world object with data
members and member methods, respectively.
4. State two differences between a class and an object.

A Class An Object
Class is a blueprint or template from Object is an instance of a class.
which objects are created.
Class is a group of similar objects. Object is a real world entity such as pen,
laptop, mobile, bed, keyboard, mouse,
chair etc.
Class is a logical entity. Object is a physical entity.
5. How do objects communicate with each other?
Ans. Objects communicate with each other through message passing.
6. How can you implement abstraction in programming terms?
Ans: Data abstraction is a method where essential elements are displayed to the user and trivial
elements are kept hidden. In Java, abstraction is achieved by using the abstract keyword for classes
and interfaces. In abstract classes, we can have abstract methods as well as concrete methods.
7. how can you implement inheritance in programming terms?
Ans: Inheritance is the procedure in which one class inherits the attributes and methods of another
class. The class whose properties and methods are inherited is known as the Parent class or base
class. And the class that inherits the properties from the parent class is the Child class or sub classs.
You use the keyword extends to identify the class that your subclass extends.
8. How is encapsulation implemented in a program?
Ans: Encapsulation in Java is the process by which data (variables) and the code that acts upon them
(methods) are integrated as a single unit. By encapsulating a class's variables, other classes cannot
access them, and only the methods of the class can access them.
9. How can you implement polymorphism in java?
Ans: Polymorphism in Java can be achieved in two ways i.e., method overloading and method
overriding. Polymorphism in Java is mainly divided into two types. Compile-time polymorphism can
be achieved by method overloading, and Runtime polymorphism can be achieved by method
overriding.
10. Why is a class called a user-defined data type?
Ans: Primitive data types are the general and fundamental data types that we have in Java and those
are byte, short, int, long, float, double, char, boolean, etc., User defined data types are those that
user / programmer himself defines.
11. State two differences between fundamental and user-defined data type.
Fundamental data type User defined data type
These are inbuilt data type provided by These are data types created by the user
the Java Language. using fundamental or user defined data
type or both.
The size of it is fixed. The size of different user-defined data
type depends upon the size of the
individual components of it
These data types are available in all parts These data types are available only as
of a program within a class. specified by the access specifiers.
12. What is an access specifier? Which two access specifier is used in a class
declaration?
Ans. Access modifiers (or access specifiers) are keywords in object-oriented languages that set the
accessibility of classes, methods, and other members. Access modifiers are a specific part of
programming language syntax used to facilitate the encapsulation of components. The public and
default access specifier is used in a class declaration.
13. Why is a class called an object factory?
Ans. A class is called an object factory because objects are created from a class. An object is an
instance of a class.
The following statements create two objects s1 and s2 of the class Student.
Student s1 = new Student();
Student s2 = new Student();
So, we have a single class Student but we can create as many objects as we want (like s1, s2, etc.)
from that single class.
This is similar to what happens in a factory. Consider a factory which produces car. They have only a
single design of a car but produce multiple cars from that single design.
Things are similar in the world of classes and objects. There is a single definition of a particular class
(like Student) but we can produce many Student objects (like s1, s2) from that single class.
14. Why is an Object called an 'Instance' of a class? Explain.
Ans. A class can create objects of itself with different characteristics and common behaviour. So, we
can say that an Object represents a specific state of the class. For these reasons, an Object is called an
Instance of a Class.
15. Why is a class known as composite data type?
Ans. A class can contain data members of various primitive and reference data types. Hence, class is
known as composite data type.
16. How will you define a software object?
Ans. A software object replaces the characteristics and behaviours of a real-world object with data
members and member methods, respectively.
17. State two rules you should follow for naming a class or Identifier.
Ans. While using names for a class the following set of rules are to be kept in mind.
1. It can have any alphabet (capital or small), digits, underscore and dollar sign characters. For
example, a, b, cat, mat123, cost_price, Topaz$ are all example of valid identifier.
2. It should not begin with digits or should not contain any special character. For example 2ab, ab#c,
top@, etc., are invalid identifiers as it either begins with a digit or contain special characters (like #,
@).
3. It cannot have a space between it. For example, Simple Interest or Selling Price are invalid class-
names as it contains a space.
4. It must not be a keyword. For example, for, while, do are invalid class-names as they are keywords
and are assigned some special function for the language.
5. It can be of any length. Even though Java gives you the flexibility to provide a huge length for an
identifier a very long name is impractical and difficult to manage.

CH 4: VALUES AND DATA TYPES


1. What do you understand by Token? Name different types of tokens.
Ans. A token is the smallest element of a program that is meaningful to the compiler. The different
types of tokens in Java are:

Identifiers
Literals
Operators
Separators
Keywords
2. 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 by the programmer to different parts of a program e.g. variables,
functions, classes,packages etc.
The rules of naming identifiers in Java.
(i) Can contain alphabets, digits, dollar sign and underscore.
(ii) Must not start with a digit.
(iii) Cannot be a Java keywords.
(iv) Can have any length and are case-sensitive.
3. What is a literal? What are the different types of literals available in Java?
Ans. Literal is a constant value that can be assigned to a variable. The different types of literals in Java
are:
1. Integer-literal or Fixed point-literal
2. Floating point-literal
3. Boolean-literal
4. Character-literal
5. String-literal
6. Null-literal
7. Class literal
4. What are keywords? Can keywords be used as a identifiers?
Ans: Keywords are the reserved words that convey a special meaning to the language compiler. No,
keywords are reserved for special purpose and must not be used as identifiers
5. State the difference between a boolean literal and a character literal.
Ans. A boolean literal may be either true or false and character literal are always enclosed within
single quotes.
6. Write any two escape sequences used in Java.
Ans. For newline :\n
For tab: \t
7. What are the different punctuators available in Java?
Ans. There are 9 punctuators available in Java.
They are: ( ) { } [ ] ; , .
8. Differentiate the two kinds of data types?
Ans: The two types of data types are: Primitive and non-primitive/composite/user define data types.
The primitive data types are the basic datatypes provided by the language. It is used to define and
hold a value in a named variable. They are: byte, short, int, long, float, double, char and Boolean.

The non-primitive/reference data types are created using primitive datatypes. It is used to store the
memory address of an object. The reference datatypes are: class, array and interface.
9. 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,
booleanJava reserve 8 bits but only use 1 bit.
10. Define variable with an example.
Ans. A variable represents a memory location through a symbolic name which holds a known or
unknown value of a particular data type. This name of the variable is used in the program to refer to
the stored value.
Example:
int mathScore = 95;
11. What do you mean by constant? Explain with an example.
Ans. The keyword final before a variable declaration makes it a constant. Its value can't be changed in
the program.
Example:
final int DAYS_IN_A_WEEK = 7;
12. Explain the term 'type casting'?
Ans. The process of converting one predefined type into another is called type casting.
13. What is the range of the following data types: byte, short, int, long, float, double,
char, boolean.
Ans: byte -2 7 to +27 -1 short -2 15 to 215 -1
int -2 31 to 231 -1 long -2 63 to 263 -1
float -3.4×1038 to 3.4×1038 double -1.7×10308 to 1.7×10308
char 0 to 65536 boolean true or false
14. Name two keywords which are also literals in Java.
Ans. They are null, true and false.
15. What do you understand by variable scope?
Ans. Variable scope is the area in which a variable is accessible or have its life.
16. Define the following:
a) Implicit type conversion
In implicit type conversion, the result of a mixed mode expression is obtained in the higher most data
type of the variables without any intervention by the user. Example:
int a = 10;float b = 25.5f, c;c = a + b;
(b) Explicit type conversion
In explicit type conversion, the data gets converted to a type as specified by the programmer. For
example:
int a = 10;double b = 25.5;float c = (float)(a + b);
17. What is Coercion?
Ans. we can say that coercion is the process of converting one data type to another data type. In a
more specific way, implicit conversion is called coercion. It is also known as type coercion.
18. Difference between primitive and non-primitive data types
The difference between primitive and non-primitive data types are as follows:
Primitive types are predefined in Java. Non-primitive types are created by the programmer and is
not defined by Java.
Non Primitive types can be used to call methods to perform certain operations, while primitive
types cannot.
A primitive type always has a value, whereas non-primitive types can be null.
A primitive type starts with a lowercase letter, while non-primitive types start with an uppercase
letter.
The size of a primitive type depends on the data type, while non-primitive types have all the same
size.

CH 5: OPERATORS AND EXPRESSIONS


1. What is the function of an operator? Name the types.
Ans: Operators are special symbols that represent operations that can be carried out on variables,
constants or expressions. An operator is mostly an symbol and sometimes a keyword also.
The different types of operators are:
 Arithmetic operator (unary operators(+,-,++,--), binary operators(+,-,*,/,%), increment/decrement
operators(++,--) )
 Relational operators (>,<,>=,<=,==,!=)
 Logical Operators (&&,||,!)
 Assignment operators(==)
 Conditional operator ?: (Ternary Operator)
 New operator(new)
 Dot(.) operator
2. What are arithmetic operators?
Ans: Arithmetic operators are used for various mathematical calculations. The result of an arithmetical
expression is numerical values. Arithmetical operators are of following types: Unary and Binary operators
and increment/decrement operator.
3. 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 (%).
4. What is assignment operator? Explain with the help of an example.
Ans:- The Assignment operator is used to assign or give a value to a variable
5. 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++
6. 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.
7. 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).
8. What are Logical operators?
Ans: The logical operators combine the result of or more than 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 it returns 0. The logical operators provided by
Java are && Logical AND, || Logical OR, ! Logical NOT.
9. What do you mean by Assignment Statement or Assignment Operator?
Ans: Assignment operator is represent by symbol „=‟. It takes the value on the right and stores it. It assigns one
value to the other.
10. 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;
11. What is Operator Associativity? What is the operator associativity of prefix/postfix
increment/ decrement operators?
Ans. Operator Associativity is a property that determines how operators of the same precedence are
grouped in the absence of parentheses; i.e., in what order each operator is evaluated.
Operator Description Associativity
++ Post-Increment
left to right
−− Post-Decrement
++ Pre-Increment
Right to left
−− Pre-Decrement
12. What are short hand operators? Explain with an example.
Ans. Java provides special operators that can be used to combine an arithmetic operation with an
assignment. For example, the expression, a = a+4;
can be written as, a += 4;
As this operator is a shorter way of expressing an expression it is also sometimes called Short hand
operators.
13. What is an accumulator?
Ans. An accumulator is a variable that the program uses to calculate a sum or product of a series of values.
14. What are counters?
Ans. Counter is a variable that keeps track of the number of times an operation has been performed.
15. Name the relational operators along with their usage in Java.

Relational Operator Usage

> Greater than


< Less than

>= Greater than or equal to

<= Less than or equal to

== Equal to

!= Not Equal to

16. Name the logical operators used in Java.


Logical Operator Name Behaviour
&& And Operator This operator joins two or
more conditions and
evaluates to true only if all
the conditions are true.
|| OR Operator This operator joins two or
more conditions and
evaluates to true only if only
one condition is true.
! Not Operator This operator is used with
one condition and if the
condition is false then this
NOT operator converted to
true and if the condition is
true then its converted to
false.
17. Give the general syntax of conditional operator and also label its operands.
Ans. It has the following general
syntax: Test-condition? statement1 : statement2;

Operand 1 Operand 2 Operand 3


18. What is the use of:
a. Dot (.) operator b. new operator
Ans. a. The dot operator is used to access or invoke individual members of a class.
b. The new operator dynamically allocates memory space for an object.
19. What are operands?
Ans: An operator acts on different data items/entities called operands. The objects of the operation are
referred as operands.
20. What do you mean by constant? How you declare a variable as constant variables.
Ans: The memory variables/locations whose values cannot be changed within the program is called
constants. The keyword final makes a variable as constants.
e.g. final int x=203;
21. Differentiate between the following:
(a) Arithmetical operator and Logical operator
Arithmetical Operator Logical Operator
Arithmetic operators are used to perform Logical operators operate on boolean
mathematical operations. expressions to combine the results of these
boolean expression into a single boolean
value.
+, -, *, /, etc. are a few examples of Arithmetic &&, ||, ! are a few examples of Logical
operators. Operators
(b) Binary operator and Ternary operator
Binary operator Ternary operator
Binary operators work on two operands. Ternary operator work on three operands.
+, -, *, /, etc. are a few examples of Binary The conditional operator ? : is a Ternary
operators. operator.
(c) Logical AND (&&) and Logical OR(||)
Logical AND (&&) Logical OR(||)
It evaluates to true only if both of its operands It evaluates to true if one or both of its operands
are true. are true.
Example: Example:
int a = 8, b = 13, c = 0; int a = 8, b = 13, c = 0;
if (a > 10 && b > 10) if (a > 10 || b > 10)
c = 10; c = 10;
else else
c = 5; c = 5;
Here, value of c will be 5 as one of the operands Here, value of c will be 10 as at least one of the
is false. operands is true.
(d) Prefix operator and Postfix operator
Prefix Operator Postfix Operator
It works on the principle of CHANGE-THEN-USE. It works on the principle of USE-THEN-CHANGE.
It is written before the operand. It is written after the operand.
Example: Example:
int a = 99; int a = 99;
int b = ++a; int b = a++;
After the execution of these two statements, After the execution of these two statements, a
both a and b will have the value of 100. will have the value of 100 and b will have the
value of 99.
(e) System.out.print( ) and System.out.println( )
System.out.print( ) System.out.println( )
It prints data to the console but the cursor It prints data to the console and places the
remains at the end of the data in the same line. cursor in the next line.
Next printing takes place from the same line. Next printing takes place from next line.
(f) Differentiate between an operator and an expression.
Ans: An operator is a symbol or sign used to specify an operation to be performed whereas an
expression is a set of variables, constants and operators i.e. an expression is a combination of operators
and operands.

CH-6: INPUT IN JAVA


1. What are the different types of variables? How are they initialized
Ans. Local variables (declared within the methods) must be declared and initialized before they are used. Local
variables are explicitly initialized and are not initialized to default values. Class and instance variables (declare
inside the class but outside the method) can only be declared and used but are assigned default values.
2. What are the default values of the following primitive types:
Ans. boolean- false
int- 0
char- ‟\u0000‟
long- 0
float- 0.0
3. What is the default value of reference data type ?
Ans. The default value of reference datatype is a null value.
4. What are the different ways to input values in Java?
Ans. The various ways to input values in an operation are:
 By using assignment
 By using function argument
 By using Scanner class
 By using Input Stream Reader class
5. What are the advantages of input through Scanner class?
Ans. Program logic is simple and Scanner class has various methods to manipulate input data. String
manipulation is easy as each word is obtained as a token and handled separately.
6. In programming what is considered to be an Input?
Ans. Programming involves taking in some data, processing it using some instructions and giving some
meaningful result. Taking in some data is called Input.
7. What is initialization of variables? Explain with a help of an example.
Ans. Initialization is the assignment of an initial value for a variable during declaration. For example, int
a=5; is a statement where 5 is stored initially into a memory location represented with the name a.
8. What do you understand by parameterized input?
Ans. The process of passing values to arguments in a method during execution is called parameterised
input.
9. What is the function of a Scanner class? In which package does it belong?
Ans. The scanner class is a class in java.util, which allows the user to read values of various types, from
either keyboard or a file.
10. Name the functions of the Scanner that is used to:
A. Accept a number of int data type  nextInt()
B. Accept a number of long data type  nextLong()
C. Accept a number of double data  nextDouble()
type
D. Accept a number of float data  nextFloat()
type
E. Accept a Boolean type of value  nextBoolean()
F. Accept a short type of data  nextShort()
G. Accept a word or string  next()
H. Accept a group of alphabets.  nextLine()
I. Accept a character  next().charAt(0)
a.
11. What is a bug? What is debugging?
Ans. A bug is an error, flaw, failure or fault in a program or system that causes it to produce an incorrect
or unexpected result, or to behave in unintended ways. The process of removing a bug is called
debugging.
12. What are the different type of errors that may occur in a Java program?
Ans. Errors in a program in Java can broadly be classified into three categories:
• Syntax errors • Logical errors • Run-time errors
13. What are syntax errors? Give two examples.
Ans. A syntax error is an error in the syntax of a sequence of characters or tokens that is intended to be
written in a particular program. The common syntax errors are:
• Missing semicolon • Mismatched braces in classes and methods.
14. What are run-time errors? Give two examples.
Ans. An error that occurs during the execution of a program is called run time error. The run-time errors
are:
• Dividing an integer by zero. • Accessing an element that is out of bounds of an array.
15. What are logical errors. Give examples.
Ans. These errors are due to the fact that the specifications are not respected. The program is compiled
and executed without errors but does not generate the desired output.
The logical errors
public static int sum(int a,int b) {
return a-b;}//return wrong value i.e. difference instead of sum
16. What are comments? Name the different types of comments used in Java.
Ans. A comment is a programmer-readable explanation or annotation in the source code of a computer
program. The different types of comments in Java are:
• Singleline comment • Multiline comment
17. What are comments? Name the different types of comments used in Java.
Ans. A comment is a programmer-readable explanation or annotation in the source code of a computer
program. There are 3 ways to give comments in Java:
Single line comment (//)
Multi line comment
/* Line 1
Line 2 */
Documentation comment
/**Line 1
Line 2*/
18. Write the difference between close( ) and exit( ).
Ans. The close( ) of the Scanner class closes the scanner and allow Java to reclaim the Scanner‟s
memory. System. exit( 0) stops the execution of the program immediately
19. Differentiate between the following:
Syntax and logical errors
Syntax Errors Logical Errors
Syntax Errors occur when we violate Logical Errors occur due to our
the rules of writing the statements of mistakes in programming logic.
the programming language.
Program fails to compile and Program compiles and executes but
execute. doesn't give the desired output.
Syntax Errors are caught by the Logic errors need to be found and
compiler. corrected by the people working on
the program.
20. What is the use of the keyword import?
Ans. import keyword is used to import built-in and user-defined packages into our Java program.
21. What is a compound statement? Give an example.
Ans. Two or more statements can be grouped together by enclosing them between opening and closing
curly braces. Such a group of statements is called a compound statement.
if (a < b) {

/*
* All statements within this set of braces
* form the compound statement
*/

System.out.println("a is less than b");


a = 10;
b = 20;
System.out.println("The value of a is " + a);
System.out.println("The value of b is " + b);
}

22. Distinguish between the following:


next() and nextLine()
next() nextLine()
It reads the input only till the next complete It reads the input till the end of line so it can
token until the delimiter is encountered. read a full sentence including spaces.
It places the cursor in the same line after It places the cursor in the next line after reading
reading the input. the input.

CH: 7 Mathematical Library Methods


1. Name the class that is used for different mathematical functions. Give an example of a mathematical function.
Ans. Math class. E.g of mathematical functions are Math.pow( ) , Math.sqrt( )
2. Predict the return data type of the following functions
Math.sqrt( ); ---- double
Math.ceil( ); ----- double
Math.round( ); ----- int or long
Math.floor( ); ----double
Math.log( ); ----- double
3. Explain the following functions
A. Math.random( )
Ans: Returns a positive double value, greater than or equal to 0.0 and less than 1.0.
B. Math.max( )
Ans: Returns the greater of its 2 arguments. Its return type is same as the type of its arguments.
C. Math.cbrt( )
Ans: Returns the cube root of its argument as a double value.
D. Math.abs( )
Ans: Returns the absolute value of its argument. Its return type is same as the type of its arguments.
E. Math.log( )
Ans: Returns the natural logarithm of its argument. Both return type and argument is of double data type.
4. Distinguish between them with suitable examples
Math.ceil( ) and Math.floor( )

Math.ceil( ) Math.floor( )
Returns the smallest double value that is greater than Returns the largest double value that is less than or
or equal to the argument and is equal to a equal to the argument and is equal to a mathematical
mathematical integer integer.
double a = Math.ceil(65.5); double b = Math.floor(65.5);
In this example, a will be assigned the value of 66.0 as In this example, b will be assigned the value of 65.0 as
it is the smallest integer greater than 65.5. it is the largest integer smaller than 65.5.

CH: 8 Conditional Constructs in Java


1. What are the three constructs that govern statement flow?
Ans: The three constructs that governs statement flow are: Sequence, Selection and Iteration constructs.
2. What is a selection/conditional statement? Which selection statement does Java provides?
Ans: A selection statement is the one that is used to decide which statement should be executed 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.
3. 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)
statement
e.g. if(marks>=80)
System.out.println(“Grade A”);
4. What are conditional statements? With which commands do you implement conditional statement in Java?
Ans. Conditional construct are specific statements that allow us to check a condition and execute certain parts of
code depending on whether the condition is true or false.
Conditional statements in Java are : if, if- else, if –else if –else and switch case.
5. When are braces optional or necessary in conditional statements?
Ans. If only one statement is to be executed depending upon a condition, giving braces is optional.
6. What are relational operators?
Ans. The relational operator allows you to test or define some kind of relation between two entities.
7. State the difference between = and ==

= ==
It is the assignment operator used for assigning a value It is the equality operator used to check if a variable is
to a variable. equal to another variable or literal.
E.g. int a = 10; assigns 10 to variable a. E.g. if (a == 10) checks if variable a is equal to 10 or not.
8. What are logical operators? Explain each of them with the help of an example.
Ans. Logical Operators are used to join more than one relational expression. The following statements explains the
usage of logical operators:
• If I have a pen AND a paper it is possible for me to write. This is an example of AND join, where both the conditions
need to be satisfied for the resultant to be true. Thus, only when I have both, pen and paper it will be possible for
me to write. Thus, AND operator is used when all conditions need to be satisfied.
• If I have a pen OR a pencil it is possible for me write. This is an example of OR join, where either of the conditions
need to be satisfied for the resultant to be true. Thus, if I have a pen I can write or if I have a pencil still I can write.
Thus, OR operator is used when either of the conditions need to be satisfied.
• If it is NOT that, I do not have a pen, it is possible for me to write. Here see how the NOT operator is used to
negate a condition.
9. What is the function of nested if?
Ans. A nested if is an if statement that is the target of another if statement. Nested if statements means an if
statement inside another if statement. This is generally used when a condition needs to be satisfied inside another
condition.
10. What is a conditional/Ternary operator? Explain with the help of an example.
Ans. This operator is used as an alternative to if statement. The ? and : are used as conditional or ternary operator.
This operator can be used to replace if else statements of the general form:
if (condition)
statement1;
else
statement2;
The above form of if can be alternatively written using ? and : as follows:
condition? statement1 : statement2;
It works in the same way as the above given form of if. That is test-condition is evaluated and if it is true, statement1
gets executed (i.e. its value becomes the value of entire expression) otherwise statement2 gets executed (i.e. its
value now becomes the value of the entire expression). For
instance, the following if statement
int c;
if (a>b)
c=a;
else
c=b;
can be alternatively written as
int c;
c = ((a>b) ? a : b);
11. Compare if and ? : .
If-else Ternary Operator
It is used when complex logic handling is necessary. It is used to offer more concise, clean and compact
code
It can have multiple statements, multiple assignments It produces an expression, and hence a single value
and expressions (more than one statements) in its can, be assigned or incorporated into a larger
body. expression.
Nested if statement is simple and fairly easy to Ternary operator in its nested form, it becomes
understand. complex and difficult to understand.
12. What is the problem of dangling-else? When does it arise? What is the default danglingelse matching and how it
is 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 than the number of else clauses. The
question then arises, with which if does the additional else clause property match.
For Example:
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 overriding 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;
}
13. What is a switch statement? How is a switch statement executed?
Ans: switch statement in a program, is used for multi-way branch. It compares its expression to multiple case values
for equality and executes the case whose value is equal to the expression of switch. If none of the cases match,
default case is executed. If default case is absent then none of the statements from switch are executed.
The syntax :
switch(expression)
{
case constants : statements;
break;
case constants : statements;
break;
default: statements;
break;
}
14. Explain with the help of an example, the purpose of default in a switch statement.
Ans: When none of the case values are equal to the expression of switch statement then default case is executed. In
the example below, value of number is 4 so case 0, case 1 and case 2 are not equal to number. Hence sopln of
default case will get executed printing "Value of number is greater than two" to the console.

int number = 4;
switch(number) {
case 0:
System.out.println("Value of number is zero");
break;
case 1:
System.out.println("Value of number is one");
break;
case 2:
System.out.println("Value of number is two");
break;
default:
System.out.println("Value of number is greater than two");
break;
}
15. 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.

16. Is it necessary to use 'break' statement in a switch case statement? Explain.


Ans: Use of break statement in a switch case statement is optional. Omitting break statement will lead to fall
through where program execution continues into the next case and onwards till end of switch statement is reached.
17. Explain 'Fall through' with reference to a switch case statement.
Ans. break statement at the end of case is optional. Omitting break leads to program execution continuing into the
next case and onwards till a break statement is encountered or end of switch is reached. This is termed as Fall
Through in switch case statement.
18. Name two jump statements and their use.
Ans: break statement, it is used to jump out of a switch statement or a loop. continue statement, it is used to skip
the current iteration of the loop and start the next iteration.
19. Explain with an example the if-else-if construct.
Ans: if - else - if ladder construct is used to test multiple conditions and then take a decision. It provides multiple
branching of control. Below is an example of if - else - if:

if (marks < 35)


System.out.println("Fail");
else if (marks < 60)
System.out.println("C grade");
else if (marks < 80)
System.out.println("B grade");
else if (marks < 95)
System.out.println("A grade");
else
System.out.println("A+ grade");
20. Give two differences between the switch statement and the if-else statement.

switch if-else
switch can only test if the if-else can test for any boolean expression
expression is equal to any of its like less than, greater than, equal to, not
case constants equal to, etc.

It is a multiple branching flow of It is a bi-directional flow of control


control statement statement
21. Differentiate between if and switch statement.
Ans: Following are the difference between if and switch statement:

i. switch can only test for equality whereas if can test for any Boolean expression.
ii. switch tests the same expression against constant values while if-else-if ladder can use different expression
involving unrelated variables.
iii. switch expression must only evaluate to byte, short, int, char, String or an enum. if doesn’t have such limitations.
iv. A switch statement will run much faster than the equivalent program written using the if-else-if ladder

CHAPTER 9 : Iteration constructs in Java


1. What are iteration statements? Name the iteration statements provided by Java?
Ans: Iteration statements are statements that allow 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.
2. Explain the term loop with an example.
Ans: A loop is a sequence of instruction s that is continually repeated until a certain condition is reached.
The following program illustrates the use of for loop.
public class Loops
public static void NaturalNumbers() {
int i; for(i=1 ; i<=10 ; i++)
{
System.out.println(i);
}
}
}
Now let us learn how the components of the loop gets executed.
Step 1: At the beginning the initialization expression is executed i.e. i=1 which assigns 1 to i.
Step 2: Then the test expression is checked i.e. i<=10 which checks whether the value of i is less than or
equal to 10.
Step 3: Since the test expression is true it enters the body of the loop i.e. System.out.println(i); is
executed which prints the current value of i in the next line.
Step 4: After executing the loop-body, the update expression i.e. i++ is executed which increments the
value of i. (The value of i becomes 2 after the execution of i++, since initially i was 1).
Step 5: After the update expression is executed, the test-expression is again evaluated. If it is true the
sequence is repeated from step number 3, otherwise the loop terminates.
3. Name the Elements that Control a Loop.
Ans: Every loop has elements that control its execution. These elements can be grouped under the
following in general:
1. Initialization Expression(s). Before entering a loop, the variable that controls the execution of it is
called initialization. The initialization of a variable may be inside a loop or outside it. Whatever it may be
it is executed only once before the iteration starts.
2. Test Expression. The test-expression (also called test-condition) is a condition, which decides whether
the loop body will be executed or not. Till the test expression evaluates to true, the loop body gets
executed otherwise the loop is terminated.
3. Update Expression(s). The update expression(s) change the value(s) of the control variable(s). The
update expression(s) is usually made to be executed; before the next iteration.
4. The Body of the Loop. The statements that are executed repeatedly (as long as the, test expression is
true) form the body of the loop
4. Give the general syntax of a for-loop.
Ans. The syntax of the for loop statement is
for (initialization expression(s); test expression; update expression(s))
{
body of the loop;
}
5. Give an example to show how multiple initialization and updation are performed in a
for loop.
Ans. int i, j;
for(i=1, j=10 ; i<=10 ; j-- , i++)
{
System.out.println(“i=” +i+ “ ”+ “j=”+j);
}
6. What is an empty for-loop. Give an example.
Ans. If the loop doesn’t contain a body, it is called an empty loop.
For example,
for(i=1;i<=100;i++);
Notice the semicolon at the end of the parenthesis, indicating that the for loop does not have body and
therefore no statement is repeatedly executed again and again.
7. State one similarity and one difference between while and do while loop
Ans. Similarity: Both the loops are generally used if the number of iterations are not known.
Difference: The while loop is an entry controlled loop and the do-while is an exit controlled loop.
8. State one similarity and one difference between while and for loop.
Ans. Similarity: Both are entry controlled loops. Difference: Initialisation, test expression and updation
can be written at the beginning of a forloop, whereas in a while loop, the initialisation is written outside
the loop, and the updation inside the body of the loop
9. What is meant by an infinite loop ?
Ans. Give one example. Ans. A loop whose test expression always results to true is an infinite loop. For
example,
for(int i=1;i!=0;i++)
{
}
10. Give the general syntax of a while-loop. How do you create infinite loops using a while-
loop structure?
Ans. The syntax of a while loop is,
while (condition or test-expression)
{
body-of-the-loop;
}
11. Give the general syntax of a do-while loop. How do you create infinite loops using do-
while loop structure?
Ans. The syntax of the do-while loop is:
do {
statement;
}while (condition);
To create an infinite you need to make the condition always result to true. For example,
do {
System.out.println(“Hello”);
}while (true);
12. Name two jump statements and their use.
Ans. The ‘break’ statement is used to exit from a loop or switch block.
The ‘continue’ statement is used to skip the remaining statements in a loop and continue with the
next iteration.
13. Differentiate Null loop and Infinite loop.
Ans: A Null loop does not contain 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++)
14. What do you mean by an infinite loop? Give an example.
Ans: Infinite loop is an endless loop whose number of iterations is not fixed.
eg: for(;;)
System.out.println(“School”);
15. 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.

Chapter 10: Nested for Loops


1. What is nested loop?
Ans. When a loop construct lies inside the body of another loop, it is called nested loop
2. What are Nested-loops? Give an example of a nested for-loop to show its functionality.
Ans. A loop within another loop is called nested loop. For example,
int x , y;
for(x=1;x<=3;x++)
{
for(y=1; y<=3 ; y++)
{
System.out.println(x+ “ ” +y);
}
}

You might also like