0% found this document useful (0 votes)
18 views

JAVA Notes_final

Java notes

Uploaded by

ilisha
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views

JAVA Notes_final

Java notes

Uploaded by

ilisha
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 39

COMPUTER APPLICATIONS

FOR ICSE CLASS X

Coverage of the entire syllabus. Almost all chapters include set


of questions and answers for better and clearer understanding
of the theoretical aspect of the subject.

Year 2021-2022

CHETNA LALWANI
INDEX

TOPICS PAGES
Introduction to Java 3
Object Oriented Programming 4
Concepts
Encapsulation And Inheritance 7
Operators and Expressions in Java 8
Input Output Stream 13
Mathematical Functions 13
Decision Making Statements 15
Iteration through Loops 17
Constructor 20
Functions 23
String 27
Array 30
Exception Handling 34
Scanner Class 35
Keywords 36
Differences 37

2
Introduction To Java

Q1.Why is java termed as a platform?


A1. Platform is the environment in which programs execute. Instead of interacting
with the operating system directly, Java programs run on the virtual machine
provided by java. Therefore, java is termed as a platform also.

Q2. What is bytecode?


A2.The programs written in java are compiled and first converted to an intermediate code called
ByteCode. It is stored in file with .class extension and is same across all platforms. It can be
executed only by Java Virtual Machine(JVM).

Q3. What is JVM?


A3. Programs written in java are compiled into Java Byte Code, which is then interpreted by a
special java interpreter for a specific platform. This java interpreter is known as the Java Virtual
Machine (JVM).

Q4. Define Compiler and Interpreter.


Compiler – It is a translator which translates the source code into machine language i.e. byte
code.
Interpreter – The software by which the conversion of the high level instructions are performed
line by line to machine language, is known as an interpreter.

Q5. What are Java APIs?


A5. The Java APIs (Java Application Programming Interface) consists of libraries of
precompiled code that programmers can use in their applications.

Q6. Write any 5 features of java?


A6. 1.Platform Independent. 2. Robust and Secure 3. Object Oriented 4.Compiler and Interpreter
5.Dynamic Binding.

Q7. Why is Java known as Platform Independent Language? OR What is WORA (Write once
run anywhere)
A7.A Java program can be compiled once into Java Byte code which is same across all
platforms. The compiled program can then be run on any computer that has an interpreter for the
Java Virtual Machine. It is therefore considered ‘Platform Independent’.

Q8. What does the term ‘syntax’ mean?


A8. Syntax are the rules governing the structure of a language statement. They specify how
words and symbols are put together to form a phrase.

Q9. Why do we use “public static void main(String[] args)” in Java?


A9. A static function can be invoked without creating an object of the class. Since all the Java
applications begin execution from the main method and other sub functions are executed from
the main method, it can be made into a static function so that it can be invoked anywhere. void is
the return data type which signifies that the main method does not return any value.
3
Q10. What are library classes? Give examples.
A10. Java development Kit contains a Java Class Library for various purposes. These are
predefined classes provided by java system present in some packages. These classes contain
related library functions like String, Math etc.
Some useful packages in the Java Class Library are:
java.io : to support classes to deal with input and output statements.
java.util: utility classes for special data structure
java.lang: essential classes like String ,wrapper classes

Q11. What is JDK? Name some JDK tools.


A11. Java Development Kit (JDK) is an environment for building java applications and applets.
It includes tools for developing and testing programs written in java.
Some JDK tools are :- the Javac compiler, the java interpreter, the applet viewer.

Q12. What is BlueJ?


A12. BlueJ is an integrated development environment(IDE) for the java programming
language, developed mainly for educational purposes. It has a viewer, editor and debugger.

Q13. Write the file extensions of source code & intermediate code(byte code)
A13. Source code: .java
Byte code: .class

Q14. Java is a case-sensitive language. Explain.


A14. Java is a case-sensitive language means it treats uppercase and lowercase characters
differently. Each character has a different Unicode. eg: Unicode of 'a' is 97 and 'A' is 65.

Q15. Why is Java a strongly-typed language?


A15. Java is a strongly-typed language because every variable must be declared with a data type.
A variable cannot start its life without knowing the range of values it can hold.

Q16. How is java compilation different from ordinary compilation?


A16. In ordinary compilation source code is converted to machine code which is different for all
the platforms. In java compilation source code is converted into byte code which is same for all
the platforms. It can be executed on any platform by the Java virtual machine.

OBJECT ORIENTED PROGRAMMING CONCEPTS


Q1. What do you understand by object oriented programming? Discuss its benefits.
A1. In object oriented programming, programs can be divided into smaller segments and then
connected together to make a whole conceptualized unit.
Benefits of OOP
A. Platform independent
B. Easy to partition
C. Reusable and modifiable software
D. Data hiding
E. Software complexity can be handled easily
4
Q2.Name and explain the principles of OOP
A2. Abstraction - It refers to representing essential features without including the background
details.
Encapsulation - The wrapping of data and methods together in a single unit called class is called
encapsulation. Data can be hidden from the users of the class. It is also known as data hiding.
Benefits- Modularity and Information hiding

Polymorphism - It is the ability of methods to take more than one form. Several method names
can be same, but manipulate different types of data.
Benefits- Function Overloading and Overriding

Inheritance - It is the process by which objects of one class acquire the properties of objects of
another class.
Benefits - It helps in code reusability

Q3. Explain object. Write the syntax for creating an object.


A3.Object is an identifiable entity with some characteristics and behaviour. An object is a self
contained element in a program that contains data.
Syntax: classname obj = new classname();

Q4. What is a class?


A4. A class is a blueprint or a prototype that defines characteristics and behaviour common to all
objects of a certain kind . It is the fundamental building block of Object Oriented Programming.

Q5. What is the syntax of class declaration?


A5.[accessspecifier] class [classname]

Q6.Why is class known as an object factory?


A6.Object is an instance of a class. Since objects of a class contain some characteristics and
behaviour, they interact with each other through its behaviour. A class is known as object factory
as it can create numerous objects of the same class.

Q7. What is the difference between Procedure Oriented Programming and Object Oriented
programming ?
A7.
Process Oriented Object Oriented
The program revolves around the code. The program revolves around the data.
It follows top-to-bottom approach. It follows bottom-to-top Approach.
Eg: Qbasic , C Eg: C++, JAVA

Q8.Differentiate between Class and Objects


A8.
Class Object
A class is a template for an object. An object is an instance of a class.
Class does not exist in the computer memory Object exists in the computer memory

Q9. What is the purpose of the new operator?


5
A9. The purpose of the new operator is to create an object, i.e. to create an instance of a class.
The keyword new allocates memory when an object is created.

Q10. Mention any two attributes required for class declaration.


A10. The keyword 'class' and the 'class name'.

Q11. Name 2 types of Java programs.


A11. 1. Java Applets - Applets are programs that run within web browsers.
2. Java Applications- A complete stand alone program that does not require a web browser
to run. It is platform independent and can run on any platform.

Q12. Explain base class and derived class.


A12. Base class is an existing class from which new classes are derived. It is also known as
Super class or Parent class.
Derived class is a new class which inherits properties from a base class. It is also known as Sub
class or Child class.

Q13. Define module.


A13. A module is a small program in itself that is designed to handle a specific task within a
larger program.

Q14. How is object implemented in software terms?


A14. In software terms the state of an object is stored in a variable and behaviour is determined
using member methods. The variables and methods are encapsulated in a class.

Q15. How are objects related to a class?


A15. A class is a fundamental block of Object-Oriented programming. A class is a blue print that
defines the variables and methods common to all objects of the same type. It combines objects
and methods for manipulating the data into one neat package.

Q16. What is an abstract class?


A16. An abstract class allows the common methods to be placed in one class without having to
write the actual implementation code. It represents the concept whose objects cannot be created.
Super class is implemented as an abstract class.
Syntax: public abstract classname()
Variables cannot be defined as abstract.
Abstract methods of super class must be defined in its sub-class.
Abstract class implements inheritance.

Q17. What is an Interface?


A17. Interface is a type of class that contains methods and variables but all variables must be
defined as final and methods can contain only declaration not body(statements).

6
Encapsulation And Inheritance
1. Encapsulation promotes data hiding. Explain
A1. Encapsulation prevents data to be accessed directly. The code and the data can only be
accessed through an interface. This is called Information Hiding. Thus encapsulation promotes
data hiding.

2. What is an initial class?


A2. A java program can contain many classes. But only one class in java program can contain
the main method. This class is called initial class.

3.Define access specifiers. Name the access specifiers in java.


A3. Access specifiers regulate access to classes, fields and methods in java. They are used to
restrict access. They determine whether a field or method in a class, can be used by another class
or sub-class.
There are 4 access specifiers in java.
Public: If a member is declared public then it is available in the same class , package and also in
other packages.
Protected: The protected members of the class are only visible in all the classes or sub-classes of
the same package.
Private: They are only available within their own class. A sub-class cannot inherit them.
Default/Friendly: It is the default access specifier. They are accessible in the same package but
not in other packages.
Access specifiers Same class Same package Subclass Other packages
Public Y Y Y Y
Private Y N N N
Protected Y Y Y N
Friendly Y Y N N

4. What are the benefits of encapsulation?


A4. The fields of a class can be made read-only or write-only. A class can have total control over
what is stored in its fields.

5. What do you mean by visibility scope and life-time of a variable?


A5. Visibility Scope : The scope of a variable is the range of program statements that can
access that variable. Scope of a variable is in the block where it is declared.
Lifetime: The lifetime of a variable is the interval of time in which storage is bound to the
variable.

6. Differentiate between Overloading and Overriding.


Overloading Overriding
Separate methods share the same name. Sub class method replaces the super class
7
method.
Overloading must have different method Overriding must have same signature.
signatures.
There is a relationship between methods There is a relationship between a super-class
available in the same class. method and sub-class method.

Q7.Name the various levels of inheritance supported by java.


 Single inheritance
 Multi-level inheritance
 Hierarchical inheritance.

Q8.Differentiate between Primitive datatype and User defined datatype


A8.
Primitive datatype User defined datatype
These are built-in datatypes. These are created by the user.
The size of these datatypes is fixed. The size of these datatypes vary as the range
depends upon their constituent members.
These datatypes are available in all parts of a The availability of these datatypes depend
java program. upon their scope.

OPERATORS AND EXPRESSIONS IN JAVA


Q1.Name the character set supported by java. Explain it.
A1.Character set supported by java is Unicode. It is a 2 byte character set which represents all
the characters present in all possible human languages.

Q2.Differentiate ASCII&UNICODE.
A2.
ASCII UNICODE
It stands for American Standard code for It stands for Universal code.
Information Interchange.
It has 0 to 256 characters. It has 0 to 65536 characters.

Some important ASCII values


A-Z 65-90
a-z 97-122
0-9 48-57
<space> 32

Q3.What is meant by token? What are the types of tokens?


A3.The smallest individual unit in a java program is called a token. Types of tokens are:
1) Identifiers
2) Keywords
8
3) Literals
4) Operators
5) Separators

Q4.What is a keyword?
A4.Keywords are reserved words that convey special meaning to the compiler. They cannot be
used as identifiers. eg. float, void, while, else, break etc

Q5.What is a literal? What are the types of literals?


A5.Li terals or constants are fixed values that do not change during the execution of the
program. Types of literals.
Integer Literal-are whole numbers that do not contain a fractional part.
Boolean Literal-can only be represented by true or false.
String Literal-are number of characters enclosed within double quotes " ".
Character Literal-is a single character enclosed within single quotes ' '.
Floating point Literal-are values which are real numbers. They can be either fractional or
exponent form. They are float or double.

Q6.What are comments? What are styles of expressing comments in java?


A6.Comment statements are explanatory statements which are non- executable. They are ignored
by the compiler. They can be used anywhere within the program. Styles of writing comments are
1. Single line comment://----------------
2. Multi line comment:/*------------------*/
3. Documentation comment:/**---------------------*/

Q7.What are an operator, operand and expression?


A7.Operator is a symbol or a letter which performs certain operations and yields a value.
Operands are variables or constants on which operations are performed by the operator.
An expression is a combination of operands and operators that produce a result on evaluation.
Eg.c=a+b; --> where c, a,& b are operands;+ & = are operators.

Q8.What are pure and mixed expressions?


A8.The expression with operands of the same data type is known as pure expression. The
expression with operands of different data type is known as mixed expression.

Q9.What is the precedence of operators? Name the operators with highest and lowest
precedence?
A9.The order in which the operands are operated by operators in an expression is known as
precedence of operators. Operators with same precedence are executed from left to right.
Operator with highest precedence--> ()
Operator with lowest precedence--> =
9
Q10.Explain with e.g. unary, binary and ternary operators?
A10. An operator that requires one operand is called an unary operator. eg. a++
An operator that requires two operands is called a binary operator. eg. a+b
An operator that requires three operands is called a ternary operator.eg. x=a>b?a:b;

Q11.Differentiate between Pre-increment and Post-increment operator.


A11.Pre-increment operator-The value of operand is first incremented and then used.
eg: int a =5; int x=++a; value of x & a will be 6
Post-increment operator-The value of operand is first used and then incremented.
eg: int a =5; int x=a++; value of x will be 5 & a will be 6

Q12.Explain ternary operator


A12.Ternary operator or conditional operator requires 3 operands. It is an alternative to if-else
statement. In ternary operator the first operand must be a conditional expression. If the condition
is true then operand2 is executed otherwise operand3 is executed.
Syntax:- var = oper1?oper2:oper3;

Q13.What is bitwise operator?


A13.Bitwise operators act as special operators for the manipulation of data at bit levels. They can
be applied on data types like byte, int, short, long and char.eg: bitwise AND(&), bitwise OR(|),
bitwise XOR(^).

Q14.Name all the primitive datatypes, their sizes in bytes & default values.
Name Size Default value
byte 1 0
short 2 0
int 4 0
long 8 0L
float 4 0.0f/0.0F
double 8 0.0d/0.0D
boolean 1 false
char 2 /u0000

Q15. Differentiate between String and Character literal.


String Character
It is a set of characters enclosed within double It is a single character enclosed within single
quotes quotes.
Stored in a variable with String datatype. Stored in a variable with char datatype.
String s="Hello World"; char ch='@';

Q16.What is the role of final keyword?

10
A16.When a variable is declared using final keyword it becomes a constant i.e. its value cannot
be changed during the execution of the program. eg: final double pi=3.14

Q17. What is a variable?


A17.A variable is a name given to memory location which holds a value of a particular datatype.
A variable can hold only a single value at a time.eg: int a =10; where a is the name of the
variable.

Q18.What is dynamic initialization?


A18.When a variable is initialized during runtime i.e. execution of the program, it is known as
dynamic initialization. eg: int a=b+c;

Q19. Name and explain the different kinds of variables in java.


A19. There are three kinds of variables in java.
1)Instance variables- The variable defined in the class are called instance variables. They are
members of the class. Each object has its own copy of instance variable and methods of the class.
Any changes made to the data members do not affect the data members of the other objects.
2) Class variables - The variables defined as static in the class are called class variables. They
are members of the class. All the objects of the class share the same copy of class variable.
3)Local variables -They are declared and utilized within the method definition. eg: counter
variables in loops, temporary variables etc.

Q20. Define type conversions. Name the types of type conversions. Explain them.
A20. The process of converting one predefined type into another is called type conversion or
type casting. There are 2 types of conversions:
a) Implicit conversion - Conversion of one primitive datatype to another by the compiler is
known as implicit conversion. Destination type is larger than the source type. It is also known
as type promotion or coercion.
E.g. : int i =5 ;
char c = 'a';//a 97ASCII value
int sum=i+c; //sum=5+97=102
b) Explicit conversion - Conversion of one primitive datatype to another forcefully by the
programmer is known as explicit conversion. Source type is greater than the destination type. It
is also known as type casting.
E.g. : int x =5, y=10;
System.out.println( (float (x+y))/2); //7.5 is the answer
Typecast operator is ' ( ) '.

21. What is meant by narrowing primitive conversion ?

11
A21. Narrowing primitive conversion converts from larger data type to a smaller data type ,
thereby losing data during conversion . Narrowing primitive conversion can throw run time or
compile time exception errors.

22. Is String considered to be a primitive data type ?


A22. String does not belong to the primitive data type . It belongs to the string class which is a
reference data type and is available in the java.lang package .

23. What value does an 8 bit memory represent ?


A23. An 8 bit memory represent a byte .Each bit can be set to two positions a zero or a one,
therefore an eight bit can represent 2^0 upto 2^8 that is 1 to 256 positions ,or it can represent
values from -128 to 127 .

24. Identify the data type in 'a'+3.


A24. It is of integer data type because char + int = int .

25. What is an identifier ?


A25. Identifiers are programmer defined tokens used for naming class, methods, variables,
objects, packages, and interfaces in a program.

26. What is punctuator ?


A26. Punctuators are used as special characters in Java . They act as punctuations within the
program.
E.G : () , : ; {} [] .

Q27.What are escape sequences? Write any two escape sequences.


A27. The backslash character in java is called the escape character because a character following
immediately after it, takes a special meaning. An escape sequence always begins with a
backward slash and is followed by one or more special characters.
\n-newline
\r-carriage return
\t- horizontal tab
\"-double quotes
\\-back slash

Q28. Explain NOT(!) operator.


A28. NOT (!) is a logical unary operator. It returns a boolean value.
eg: !(5>7) returns true

Q29. Explain Logical AND(&&) and Logical OR(||)


A29. They are used to combine two or more relational expressions. They return a boolean value.

12
Truth table for AND Truth table for OR
0 0 0
0 1 0
1 0 0
1 1 1
0 0 0
0 1 1
1 0 1
1 1 1

INPUT/OUTPUT STREAM
Q1.Name the input/output streams used in java.
A1.System.in: The input stream is connected to the keyboard by the System class.
System.out: refers to the standard output stream.
System.err: refers to the output stream for error messages.

Q2. Write a java statement to input/read the following from the user using the keyboard.
i) Character char ch=(char)br.read();
ii)String String str=br.readLine();

Q3.What are wrapper classes?


A3.In java, String is a reference data type. To convert numeric values to String and vice-versa,
Java provides respective reference type classes. The conversions can be done using the "Wrapper
class". They are available in java's standard library java.lang.
Wrapper Class Data type
byte Byte
short Short
int Integer
long Long
float Float
double Double
char Char
boolean Boolean

Q4.What is a stream?
A4. A stream is an abstraction which either sends or receives information.

Q5. Name the three classes that play with character data.

13
A5. i)Character ii)String iii)StringBuffer

MATHEMATICAL FUNCTIONS
The Math class is defined in the java.lang package. The methods in the Math class are static
methods. The general syntax is: Math.functionname();

METHOD DESCRIPTION EXAMPLE


Math.pow() Returns the value of the first double n = Math.pow(2,4)
argument raised to the second n = 16.0
argument
Math.sqrt() Returns the square root of a double n=Math.sqrt (25)
positive number n=5.0
Math.abs() Returns the absolute value of a double n =Math.abs(-2.5)
number n=2.5
Math.max() Returns the maximum of the 2 double n = Math.max(-25,-10)
values n= -10
Math.min() Returns the minimum of the 2 double n = Math.min(3.5,2.6)
values n= 2.6
Math.floor() Returns the nearest whole double n= Math.floor(2.56)
number that is less than or n=2.0
equal to the value
Math.ceil() Returns the nearest whole double n = Math.ceil(2.56)
number that is greater than or n= 3.0
equal to the value
Math.rint() Returns the truncated value double n = Math.rint(2.56)
rounded off to the next integer n=3.0
and returns double value.
Math.round() Rounds a float & returns an double n = Math.round(2.56)
integer value n=3
Math.sin() Returns the sine of a given double n = Math.sin(3.0)
angle value in radians
Math.cos() Returns the cosine of a given double n = Math.cos(3.0)
angle value in radians
Math.tan() Returns the tangent of a given double n = Math.tan(3.0)
angle value in radians
Math.log() Returns the natural logarithm double n = Math.log(0.256)
of the specified double value
Math.exp() Returns the value e to the double n=Math.exp(3.0)
power of x
Math.random() Returns randomly generated double n= Math.random()
number between 0.0 and 1.0 n= (int)(Math.random()*6)+1
Returns randomly generated
number between 1 and 6

Q)What is symbolic constant? Name the symbolic constants of the Math class.
14
A) A symbolic constant is a variable whose value does not change during the entire lifetime of
the program. The symbolic constants of the math class are :
Math.e represents e, the base of the natural logarithm which is approximately 2.71828
Math.pi represents the ratio of the circumference of a circle to its diameter as 22/7 or 3.14.

DECISION MAKING STATEMENTS

Q1. What is a statement?


A1. Statements are the instructions given to the computer to perform any kind of action.
Statements form the smallest executable unit and terminated with semi-colon.

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


A2.Compound statements are those, which contains one or more statements grouped together
within curly braces. eg: loops, methods, if(), switch() etc.

Q3. What are the three constructs that govern statement flow?
A3. The three constructs that governs statement flow are: Sequence, Selection and Iteration
constructs.

Q4. What is a selection/conditional statement? Which selection statement does Java provides?
A4. 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.

Q5. What is an ‘if’ statement? Explain with an example.


A5. 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”);

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


A6. 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.

Q7. Write one advantage and one disadvantage of using ?: in place of an if.
A7. Advantage: It leads to a more compact program.
Disadvantage: Nested becomes difficult to understand or manage.

Q8. What do you understand by nested ‘if’ statements? OR


Explain with an example the if-else-if construct.
A8. When an if statement is placed within another if, it is known as nested if-else-if structure. It
takes the following general form.
15
if (condition 1)
{statements}
else if (condition 2)
{statements }
else if (condition 3)
{ statements }
eg:
public void check (int a, int b)
{
if (a>b)
System.out.println (“a is greater”);
else if(a==b)
System.out.println (“both are equal”);
else
System.out.println (“b is greater”);
}

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


A9. This problem of dangling –else arises when in a nested if statement, number of if’s is more
than the number of else clause. The question then arises, with which if does the additional else
clause property match. It can be resolved using '{}'. For Example
if (ch>=’A')
if(ch<=’Z')
++upcase;
else
++other;

Q10. Compare and contrast IF with?:


A10.
If statement Ternary Operator
It can have more than one statement in a block It can return only one value.
Consumes much space. It makes program concise and small.
In nested form it is not complex. In nested form it is more complex.

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


A11. Switch statement successively tests the value of an expression against a set of integers or
character constants. When a match is found, the statements associated with the constants are
executed. Syntax:
switch (expression)
{
case constants : statements; break;
case constants : statements; break;
default: statements;
}

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


A12. In switch statement when a match is found the statement sequence of that case is executed
16
until a ‘break’ statement is found. When a ‘break’ statement is found program execution jumps
out of the switch block.

Q13. What is a control variable in a switch case?


A13. 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. The control variable can only be of type
byte, short, int, long or char.

Q14. What is a “fall through”?


A14. In a switch statement, the matching case is executed, till it encounters a break statement.
The control flows to the next case, in the absence of a break statement, it is known as ‘fall
through’.

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


A15. Advantage: More efficient in case a value is to be tested against a set of constants.
Disadvantage: It can perform tests only for equality between variable and range of values. It
cannot use float and string values.

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

Q17. Explain, with the help of an example, the purpose of default in a switch statement.
A17. In switch if none of the cases matches the switch expression, then the default statement is
executed. The default statement is optional and is the last statement in switch. If no case is true
and default statement is not present, no further action is taken.
switch(n)
{
case 1: System.out.println(“Sunday”); break;
case 2: System.out.println(“Monday”); break;
case 3: System.out.println(“Tuesday”); break;
default : System.out.println(“Invalid Input”);
}

Q18. Differentiate between if and switch statements.


A18.
IF ELSE SWITCH CASE
Logical expressions can be used Logical condition cannot be used
Uses integer and float values. Accepts only integer and character values.
More than one variable can be used for Compound statements are executed on the
comparisons and conditions. basis of the value of the same variable.
The keyword else is used. The keyword default is used.
There is no break statement. After every case statement, the break statement
is used.
17
ITERATION THROUGH LOOPS

Q1. What is iteration? Name few iteration statements.


A1. Iteration statements execute a block of code repeatedly until a termination condition is
satisfied. Iteration statements are for, while and do-while loops.

Q2. What is the difference between entry controlled or exit controlled loops? OR
What is the difference between while and do-while loops.
A2. Entry controlled loop : In this construct the test expression is evaluated first and then the
statements are executed. The loop is not executed if the condition is false for the first time .
eg. for, while loop
Exit controlled loop: In this construct the test expression is evaluated after the execution of the
statements. The loop executes at least once even if the condition is false for the first time.
eg: do-while loop.

Q3. What is an infinite loop? OR what is an endless loop.


A3.A loop that never terminates is known as infinite loop.
Eg: for(i=1;i<=10;)
{ System.out.println(“Infinite Loop”);
}

Q4. What is a null loop ? OR What is empty loop?


A4. A for statement, which doesn’t include any statement as body of the loop is called null loop
or empty loop.
A null loop is also called a delay loop which does not repeat the execution of any statement but
keeps the control engaged until the iterations are completed.
Eg: for(i=1;i<10;i++);

Q5. Explain for loop.


A5.A for loop is used for a fixed number of iterations. It is an entry controlled loop which is
executed for all values from initial value to the final value, with the increment/decrement of the
step value.
Syntax: for(initial expression; test expression; update expression)
{loop body;}
Where initial expression is executed once, test expression is evaluated at every iteration and the
update expression is executed at the end of each iteration.

Q6. Explain While loop.


A6. While loop is used when the number of iterations are unknown. It is an entry controlled loop
which repeats set of statements while the expression that controls it is true.

18
Syntax:
Initialization;
while(condition)
{statements;
}
Q7. Explain do while loop.
A7.It is an exit controlled loop. It is used when the number of iterations are unknown. It first
executes the statements and then checks the conditions. So it executes the loop at least once.
Syntax:
initialize;
do{
Statements;
}while(condition);

Q8.What are nested loops?


A8.A loop within a loop is known as nested loop. For every iteration of outer loop, inner loop
executes n times.
Eg: int a=0;
for(int i=1;i<=3;i++)
{
for(int j= 1;j<=5;j++)
{ a++;
}
}
Value of a after execution : 15

Q9. Give differences and similarities between while and for, while and do-while
While loop For loop
Number of iterations are unknown Number of iterations are known
All the expressions are written on different All the expressions are written on the same
lines. line.
Similarity : Both are entry controlled loops

While loop Do while loop

It first checks the condition and then executes It first executes the statements and then checks
the statements the condition
It is entry controlled loop It is exit controlled loop
It will not execute if the condition is false. It is executed at least once even if the condition
is false.
Similarity : Both the loops are used when the number of iterations are not known.

Q10. Explain break statement


A10. It helps in early termination of the loop. A break statement terminates the loop and
proceeds to execute the first statement outside the loop. If break statement is found in nested
loop it terminates the inner loop.
Eg: int sum=0;
19
for(int i=1;i<100;i++)
{ sum= sum + i;
if(sum= =15)
break;
}
System.out.println("out of loop"+sum);
Output: out of loop15 // the loop will terminate when sum=15

Q11. Explain continue statement.


A11. The continue statement forces the next iteration of the loop and skips rest of the statements
following the continue statement within the loop. It helps in early iteration of the loop. Continue
statement cannot be used in switch.
Eg: for(int i=1;i<=5;i++)
{ if(i= = 3)
continue;
System.out.print(i+" ");
}

Output: 1 2 4 5

Q12. What are jump statements ? Name them.


A12. Jump statements are used to transfer control from one program segment to another. Java
provides four jump statements.
A. return B. break C. continue D. System.exit(0)

Q13. Explain return and System.exit(0) statements.


A13. The return statement is used to transfer control back to the method from where the call
was made. It is used mainly in functions.
The System.exit(0) method terminates the execution of the program. The statement can be used
anywhere in the program. Ihe integer 0 is passed as an argument, which indicates a normal
termination of the program.

CONSTRUCTORS
Q1.What is constructor? Why do we need a constructor as a class member?
A1. A class is a combination of member variables and methods. The member variables are
initialized by a constructor. A constructor is a member function that is automatically invoked,
when the object is created of that class. It has the same name as that of the class name and has no
return type. Constructor is needed as a member of the class to initialize objects upon creation i.e.
to initialize data members of the class.

Q2. Why does a constructor should be defined as public?


A2. A constructor should be defined in public section of a class, so that its objects can be created
in any function.

20
Q3. Explain default constructor or non-parameterized constructor.
A3. The constructor that accepts no parameters to initialize the data members of the class is
called the default constructor. If we do not explicitly define a constructor for a class., then java
creates a default constructor for the class. Example:
class ant
{
int x,y;
public ant()
{ x=0;y=0;}
public static void main()
{ant nc=new ant();}
}}

Q4. Explain the Parameterized constructor?


A4. A constructor that accepts parameters to initialize the data members of the class is known as
parameterized constructor.
Example:
public class result
{
int per;
int tot;
public result (int p)
{
per=p;
tot=0;
}
}

Q5. Give a syntax/example of constructor overloading. Define a class, which accept roll number
and marks of a student. Write constructor for the class, which accepts parameter to initialize the
data member. Also take care of the case where the student has not appeared for the test where
just the roll number is passed as argument.
A5. class student
{
int roll;
float marks;
student(int r, float m) // constructor with two argument.
{
roll=r;
marks=m;
}
student (int r) // constructor with one argument
{
roll=r;
marks=0;
}
student() // default constructor
21
{
roll=0;
marks=0;
}
}

Q6. Mention some characteristics of constructors.


A6. The special characteristics of constructors are:
(i) Constructors should be declared in the public section of the class.
(ii) They are invoked automatically when an object of the class is created.
(iii) They do not have any return type not even void.
(iv)Constructors should have the same name as that of the class.

Q7. State the difference between Constructor and Method.


A7.
Constructor Method
It has the same name as class name It has different name than class name.
It has no return type. It may or may not have a return type.
It is invoked using the new operator. It is invoked using the dot operator.

Q8. Enter any two variables through constructor parameters and write a program to swap and
print the values.
class swap
{
int a,b;
swap(int x,int y)
{
a=x;
b=y;
}
public void main(String args[])
{
int t=a;
a=b;
b=t;
System.out.println(“the value of a and b after swapping : “+a+” “+b);
}
}

Q9. What are the types of Constructors used in a class?


A9. The different types of constructors are as follows:
i. Default Constructors.
ii. Parameterized Constructor.
iii. Copy Constructors.

Q10. Define Copy constructors.


A10. A copy constructor initializes the instant variables of an object by copying the initial value
22
of the instance variables from another objects. e.g.
class xyz
{
int a,b;
xyz(int x,int z)
{
a=x;
b=y;
}
xyz(xyz p)
{
a=p.x;
b=p.y;
}
}

Q11.What do you mean by constructor overloading?


A11. When two or more constructors are defined in a class with different parameter list it is
known as constructor overloading.
class student{
int rno;
float marks;
student (int r, float m) //constructor with 2 arguments.
{
rno=r;
marks=m;
}
student () //constructor with no arguments.
{
rno=0;
marks=0.0f;
}
public static void main()
{
student s1=new student(); //calls default constructor
student s2=new student(15,85.5); //calls parameterized constructor
}
}

FUNCTIONS
Q1. What is a Function? Q. Explain Functions/Methods definitions with syntax?
A1: Functions are the modules from which java programs are built. They exist inside a class.

23
A function must be defined before it is used anywhere in the program.
Access specifier Modifier return-type function-name (parameter list)
{
body of the function
}
[access specifier] can be Public, Protected or Private. [Modifier] can be one of final, native,
synchronize, transient, volatile. Return-type specifies the type of value that the return statement
of the function returns. It may be any valid Java data type. Parameter list is comma separated list
of variables of a function.

Q2. What is the use of void before function name?


A2. void data type specifies an empty set of values and it is used as the return type for functions
that do not return a value. Thus a function that does not return a value is declared as follows.
void functionname(parameter list)

Q3. Define Function prototype/method header and Function signature.


A3. The function prototype is the first line, which contains the access specifier, return type,
method name and a list of parameters. It is also known as method header.

Function signature basically refers to the number and types of the arguments; it is the part of
the prototype.

Q4. Why is main () function so special?


A4. 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.

Q5. Explain the function of a return statement?


A5. The return statement is useful in two ways.
1. An immediate exit from the function is caused as soon as a return statement is encountered
and the control is returned back to the main caller.
2.It is used to return a value to the calling code according to the type specified.

Q6. Write advantages of using functions in programs.


Ans: (i) functions lessen the complexity of programs (ii) functions hide the implementation
details (iii) functions enhance reusability of code

Q7. Difference between Actual argument and Formal argument?


A7. The parameters that appears in function call statement are called actual argument .
The parameters that appears in function definition are called formal parameter.

Q8. What are static members?


A8. The members that are declared static are called static members. These members are
associated with the class itself rather than individual objects. The static members and static
methods are often referred to as class variables and methods.

24
Q9. What is the use of static in main() methods?
A9. (i) They can only call other static methods. (ii) They can only access static data. (iii) They
cannot refer to this or super in any way.

Q10. Explain the term “pass by reference”?


A10. In pass 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.

Q11. Differentiate between call by value and call by reference?


A11. In call by value, primitive data types are passed by value. If any change is made in the
formal parameter, it does not reflect in the actual parameter.

In call by reference, data types like objects and arrays are passed by call by reference. Any
changes made in the formal parameter is reflected in the actual parameter.

Q12. What is the difference between pure and impure functions?


A12. Pure Function: The functions which return values and do not change the state of the
objects are called pure functions. Pure functions are also called Accessor methods.

Impure Function: These functions change the state of the arguments they have received. Impure
functions are also called Mutator methods

Q13. How are following passed in Java?


(i) Primitive types (ii) reference types
A13. (i) pass by value, (ii) pass by reference.

Q14. What does functions overloading mean? What is its significance?


A14. The process of having two or more methods within a class with the same name but different
parameter list is known as Function overloading. It implements polymorphism. It reduces the
number of comparisons in a program and thereby makes the programs run faster.

For example following code overloads a function area to computer areas of circle, rectangle and
triangle.
float area (float radius) //circle
{
return (3.14 * radius * radius);
}
float area (float length, float breadth) //rectangle
{
return (length*breadth);
}
float area (float side1, float side2, float side3) //area of triangle
{
float s = (side1 + side2 + side3)/2;
float ar = Math.sqrt(s * (s- side1)*(s-side2) *(s-side3));

25
return (ar);
}

Q15. What is ‘this’ keyword? What is its significance?


A15. The “this” keyword is used to refer to currently calling objects. It is used to resolve name
conflict between local and instance variables.

Q16. What do you mean by recursive function?


A16. When a method is called inside its own definition the process is known as function
recursion and this function is called recursive function.

Q17. Differentiate between


A) Call by Value and Call by reference
Call by Value Call by Reference
Changes made to the formal parameters do not Changes made to the formal parameters are
reflect back to the actual parameters reflected back in the corresponding actual
parameters
Primitive data types are passed by call by value Reference data types like objects and arrays are
passed by call by reference.
Formal parameters are copies of actual Formal parameters are references to the actual
parameters parameters.
The function creates its own copy of argument The function does not create its own copy of
values and then uses them. argument values.

B)Instance and Local Variables


Instance variables Local variables
They are declared in the class outside the They are declared inside a method or block.
methods.
The scope of the variable is available to the The scope of the variable is restricted within
entire class and its members. the block or method they are declared.

C) Instance and Static Variables


Instance Static
They are not declared with the keyword static. They are declared with the keyword static.
All instances have an individual copy. All instances share the same copy.
The lifetime of instance variables depends The lifetime of static variables depends upon a
upon an object. class.
They can be accessed only by an object. They can be accessed without an object.

Q18. Write the function prototype for the function sum that takes an integer argument x as its
argument and returns a value of float data type.
A18.public float sum(int x)

Q19.What is early(static) binding and late (dynamic) binding?

26
A19.When the function call in a program is decided during compilation it is known as early or
static binding. When the function call in a program is decided during the execution of the
program it is known as late or dynamic binding.

Q20.What is the difference between a parameter and an argument.


A20.A parameter is a variable defined by a method that receives a value when the method is
called. An argument is a value that is passed in a function when a method is invoked.

Q21.i)If a function contains many return statements, how many of them will be executed?
ii)Which OOP principle implements function overloading?
A21.i)only one return statement will be executed.
ii) Polymorphism

STRINGS
Q1. Define String?
A1. A string is a sequence of characters written within double quotes. e.g. “Happy New Year”,
“Computer Application” etc.

Q2. What is String Buffer? How we create a String Buffer?


A2. String Buffer is a type of memory location, which allows reasonable space to contain a string
such a way that any change brought affects the same string.
String Buffer is created as follows: StringBuffer p=new StringBuffer (“Computer”);

Q3. Differentiate between String and StringBuffer objects.


A3.
String StringBuffer
Once a string is created you cannot change the StringBuffer objects can be altered on the same
characters that comprise the string instance after creation
String objects are immutable StringBuffer objects are mutable
New object is required to alter the string. New object is not required

Q4. Write down the purpose of the following string functions: toLowerCase(), toUpperCase(),
replace(), trim(), equals(),equalsIgnoreCase(), length(), charAt(), concat(), substring(), indexOf(),
lastIndexOf(), compareTo(), startsWith(), endsWith()
A4. The purpose and syntax of the following string functions are:
toLowerCase(): This function converts all the characters of the string in lower case.
eg: String n="AMITABH";
n=n.toLowerCase();
System.out.println(n); output : amitabh

toUpperCase (): This function converts all the characters of the string in upper case.
eg: String n="Amitabh";
n=n.toUpperCase();

27
System.out.println(n); output: AMITABH

replace (): This function replaces all the occurrence of a character with another one.
String n="DAD";
n=n.replace('D','G');
System.out.println(n); output: GAG

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 returns true if equal else false.
String s1="AMIT";
String s2="amit";
System.out.print(s1.equals(s2)); output: false

equalsIgnoreCase():This function is used to compare two strings and returns true if the strings
are equal after ignoring cases and false if they are unequal.
String s1="AMIT";
String s2="amit";
System.out.print(s1.equals(s2)); output: true

length(): This function returns the number of characters present in the string.
String s="AMITABH";
System.out.print(s.length()); output: 7

charAt(): This function returns the nth character of the string.


String s="AMITABH";
System.out.print (s.charAt (2)); output: I

concat(): This function concatenate/join two strings.


String s1="AMITABH ";
String s2="BANERJEE"
System.out.print(s1.concat(s2)); output: AMITABH BANERJEE

substring(): This function returns the substring starting from the nth character of the string.
String s="AMITABH";
System.out.print(s.substring(3)); output:TABH
This function also returns the substring starting from the nth character up to the mth character
without including the mth character of the string.
String s=”AMITABH”;
System.out.print(s.substring(2,4)); output:IT

indexOf (char): This function returns the position of the first occurrence of a character in the
string.
String s="AMITABH";
28
System.out.print(s.indexOf(‘A’)); output:0

indexOf(char,int):This function also returns the position of the character from the nth position of
the string.
System.out.print(s.indexOf(‘A’,2)); output:4

lastIndexof(char):This function returns the position of last occurrence of given character in the
string.
String s="AMITABH";
System.out.print(s.lastIndexOf(‘A’)); output:4

compareTo(): This function returns negative if first string is less then second string, positive if
greater and zero if equal.
String s1="AMIT";
String s2="SUMIT";
System.out.print(s1.compareTo(s2));

startsWith(String): This function returns true if the string starts with specified parameter string.
String s1="SUM";
String s2="SUMIT";
System.out.print(s2.startsWith(s1)); output:true

endsWith(String): This function returns true if the string contains a suffix specified by parameter
string.
String s1="MIT";
String s2="SUMIT";
System.out.print(s2.endsWith(s1)); output:true

Q5. What is the difference between equals() and equalsIgnoreCase() string functions?
A5. Both the functions are used to compare strings, the difference being that equals ()
distinguishes between upper case and lower case version of a character, whereas
equalsIgnoreCase () carries out comparison ignoring the case of characters. Both the functions
return a boolean value.

Q6. Differentiate between equals () and compareTo() methods.


A6.
Equals() compareTo()
It checks if two strings are equal or not It compares the two strings and returns the
difference in the values based on the ASCII
values of the distinct characters.
Returns true if strings are equal otherwise false This function returns negative if first string is
less then second string, positive if greater and
zero if equals.
Returns Boolean value Returns integer value
E.g.:” Hello”. Equals(“Hello”); returns true e.g.: “THAN”.compareTo(“THEN”); returns -4

29
Q7. Differentiate between toLowerCase () and toUpperCase () methods.
A7. 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, whereas toUpperCase ()
method change the current string object to its equivalent Upper Case.

Q8. What is the difference between the length () and capacity () string function.
A8. The function length () returns the number of character in a string.
capacity () returns the maximum number of characters that can be stored in a string object.

Q9.Write a statement for the following.


A. Extract the second last character of a string stored in variable wd.
char k=wd.charAt(wd.length()-2);

B. Check if the second character of a string is in uppercase.


boolean b=Character.isUpperCase (s.charAt (1));

C. Find and display the last position of a space in a string.


System.out.println(str.lastIndexOf (' '));

D.To extract the last seven characters of a string.


String t= s.substring(s.length()-7);

Q10. State the difference between = = operator and equals () method.


A10. = =: 1. It is a relational operator. 2. It tests the value on the right side with value on the left
side.
equals (): 1. It is a string function. 2. It compares two strings and gives the value as true or false.

Q11. Differentiate between length &length () function


Ans.The length property is used to count number of elements in an array. It is an intrinsic
variable of array provided by Java.
eg: int a[] ={1, 2, 3,4,5} ;
int l=a.length;
The length () function is used to count number of characters in the string. It is the function of
string class.
Eg: String s="Hello World";
int l=s.length ();

Character class provides various methods to manipulate the character class type
Method Description
static boolean isDigit(char ch) Returns true if ch is digit else returns false
static boolean isLetter(char ch) Returns true if ch is letter else returns false
static boolean isLetterOrDigit(char ch) Returns true if ch is letter or digit else returns
false
static boolean isLowerCase(char ch) Returns true if ch is in lowercase else returns
false
static boolean isUpperCase(char ch) Returns true if ch is in uppercase else returns

30
false
static boolean isSpace(char ch) Returns true if ch is a white space else returns
false
static boolean toLowerCase(char ch) Returns lowercase equivalent of ch
static boolean isUpperCase(char ch) Returns uppercase equivalent of ch

ARRAYS
Q1. What do you understand by Arrays? How you declare an Array?
A1. An Array is a collection of variables of the same data type that are referenced by a common
name. Array can be declared by the following statements: int n [] =new int [10];

Q2.Write the general syntax of SDA.(Single Dimensional Array)


A2. Datatype arrayname[array size] = {initial data values};

Q3. What are the disadvantages and advantages of arrays?


A3. Advantages:
1. It can store many values under a single name.
2. Every element can be accessed by its index using for loop
3. Searching and sorting of elements is easier.
Disadvantages:
1. It can store values of one data type only.
2. Length of the array is fixed.

Q4.What are the different types of arrays?


(i) Single Dimensional Arrays: A list of items can be given one variable name using only one
subscript .e.g.: int a [] =new int[10];
(ii) Multi Dimensional Arrays: The elements in multi-dimensional array are accessed by 2
subscripts.eg: int a [][] = new int [3][3]; //3 rows & 3 columns

a[0][0] a[0][1] a[0][2]


a[1][0] a[1][1] a[1][2]
a[2][0] a[2][1] a[2][2]

Initialization of 2-D array : int[][]={{1,2,3},{4,5,6},{7,8,9}};

1 2 3
4 5 6
7 8 9

Q5.Explain the length property of array. Give example.


A5. The length property of the array is used to get the number of elements in an array. The
length field of the array returns the size of the array.
31
E.g.: int a [] = {1, 4, 3, 7, 8};
int len = a.length; len=5

Q6. How can arrays be initialized? Give example.


A6. Array can be initialized at the time of declaration by providing the value list at the same
time. e.g.: String [] r= {“Jack”,”Queen”,”King”,”Ace”};

Q7. What do you mean by Array Instantiation?


A7.To instantiate (or create) an array, write the new keyword, followed by the square brackets
containing the number of elements you want to have.
int arr[]=new int [20];
We can instantiate an array by directly initializing it with data.
int arr [] = {10, 20, 30, 40, 50};

Q8. What do you understand by out-of-bound subscripts?


A8. The subscripts other than 0 to n-1 for an array having n elements are called out-of-bounds
subscripts.

Q9. Name the error which is caused when the specified position exceeds the last index of the
array.
A9. Error raised is ArrayIndexOutOfBoundsException.
Eg: int a [] = {2, 4, 8,10};
For (int i=0; i<=5; i++)//Index 5 is not available.
{…..}

Q10. What do you mean by Binary Search?


A10. The array is divided into two segments and the middle element is compared. If the search
value is not located on middle element then either of the 2 halves is checked depending on the
search value. It reduces by half the number of items to check with each iteration, so locating an item
takes lesser time.

Q11. Differentiate between linear search and binary search techniques


A11.

Linear Search Binary Search


Can search on both , sorted and unsorted data Can search only when the array is sorted.
Compares the elements of the array in The array is divided into two segments out of
sequential order till a match is found. which only one needs to be searched
It is time consuming for large no. of elements It is a faster process for large no. of elements

Q12. State the conditions under which Binary Search is applicable?


A12. For Binary Search the array elements must be sorted, and lower bound and upper bound of
the list must be known.

32
Q13. Comment on the efficiency of linear search and Binary Search in relation to the number of
element in the list being searched?
A13. 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 comparisons 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 tries to locate the search item in minimum possible comparisons, provided the
array is sorted. This technique proves efficient in nearly all the cases.

Q14. What do you mean by sorting?


A14. Sorting of an array means arranging the array elements in a specified (ascending or
descending) order.

Q15. What is Selection sort?


A15. In selection sort it finds smallest (or maximum) value, swaps it with the value in the first
position, and repeats these steps for the remaining unsorted array. The process repeats until the
entire array is sorted.
It makes sorting inefficient on large lists.

Q16. What is Bubble sort?


A16. 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.

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


A17. 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.

Q18. Name the search or sort algorithm that:


A. makes n-1 passes to sort the whole array checking the adjacent elements in every pass:
Ans. Bubble sort
b. Compares the sought key with each key element of the array.
Ans. Linear Search

Q19. Show the representation of the given array in memory after the second iteration of selection
sort 4 3 2 5 7 6 8
Ans. Using Selection sort

4 3 2 5 7 6 8

After 1st iteration

2 3 4 5 7 6 8

After 2nd iteration

33
2 3 4 5 7 6 8

Q20. Determine the number of bytes required to store the following arrays:
A20. int a [23]
Ans. 23*4=92 bytes
B. char b [17]
Ans. 17*2=34 bytes.

Q21.What is a subscript?
A21. An integer that is used to identify a specific memory location whose value can vary from 0
to n-1 for an array of n elements.

Q22. What is a subscripted variable?


A22. A user defined name to identify a set of adjacent memory locations is called a subscripted
variable or array variable.

Q23.What do you understand by the basetype of an array?


A23. The datatype of an array is known as the basetype of the array.

EXCEPTION HANDLING

Q1. What are the different types of errors in Java?


A1. 1. Compile time errors: These errors arise during program compilation because of incorrect
syntax used within the program.
Eg: missing semicolon, spelling mistakes in keywords, case mismatch, use of = = inplace of =
2. Run-time errors: These errors arise during the execution of the program. These errors are also
known as exceptions.
Eg: Division by zero, square root of a negative number, exceeding the bounds of an array
3. Logical errors: An error that occurs during the planning of the program’s logic is known as
logical error and the desired output will not be obtained. They are not detected during execution
or compilation.

Q2. What is an exception? What is exception handling? What are the ways to handle an
exception?
A2. An exception is an event, which during the execution of the program, disrupts the normal
flow of the program’s instructions.eg: division by zero, exceeding the bounds of the array.
Exception handling is a programming language construct or computer hardware mechanism
designed to handle the occurrence of exceptions, special conditions that change the normal flow
of program execution.
There are 2 ways in which exceptions can be handled:
Using try , catch , finally blocks.
throws keyword

Q3. What is exception handler?


A3. The block of code that can handle the exception is called exception handler.
34
Q4.Name any 3 exception handling classes.
A4. Exception handling classes are:
1. ArithmeticException
2. ArrayIndexOutOfBoundsException
3. NumberFormatException
4. IOException
5. InputMismatchException
6. NoSuchElementException

Q5. Explain try and catch and finally blocks with example.
A5. The try and catch block is used for exception handing. The try block contains the normal
code that is to be executed and in which exceptions may occur. The catch block
contains the code to be executed if an exception is thrown by the try block. There can be
multiple catch blocks for a single try block. The finally block contains the code that has to be
executed , irrespective, whether an exception has occurred or not.
Eg:
class Temp
{
public void main(int a ,int b)
{
try
{
System.out.println(“division”+a/b)’
}
catch(Exception e)
{
Sytem.out.println(“error occurred”+e);
}
finally
{
System.out.println(“finally block is executed “);
}
}
}
Exception will be thrown if the value of variable b is zero and it will be handled by catch block.

Q6.What is a bug ? What is debugging?


A6. An error in a program is termed as a bug. Removing the error in the program is known as
debugging.

Q7.Differtiate between Compile-time and Run-time errors


A7.

35
Compile time error Run time error
The errors occur due to incorrect syntax in the The errors occur during execution of the
program program
Inspite of the errors in the program, the The program cannot be executed.
program can be compiled.
Errors occur during compilation of the Errors occur only during run-time
program.

Q8.State the advantages of Exception Handling.


A8. Exception handling separates error handling code from normal code.
It clarifies code and enhances readibility.
It makes clear, robust and fault tolerant programs.

SCANNER
The Scanner class is defined in the java.util package. A Scanner class object has to be created
before using the class.
Scanner sc= new Scanner(System.in);
The Scanner class works on the principle of tokens. A token is a series of characters that ends
with a delimiter. The default delimiter is a whitespace. For each of the primitive datatypes, there
is a corresponding next() and hasNext() methods that return the next token. If a value cannot be
interpreted by the method, an InputMismatchException is thrown. The advantage of using
Scanner class is that it is able to read all primitive datatypes from System.in or from a file.
The default delimiter can be changed as follows:
sc.useDelimiter(\\s*,\\s*);

Method Returns
int nextInt() Returns the next token as an int.
long nextLong() Returns the next token as long.
double nextDouble() Returns the next token as double.
float nextFloat() Returns the next token as an float.
String next() Returns the next token as string till whitespace
String nextLine() Returns the rest of the current line as string,
excluding any line separator at the end.
void close() Closes the scanner

Method Returns
boolean hasNextInt() Returns true if the next token is an int.
boolean hasNextLong() Returns true if the next token is long.
boolean hasNextDouble() Returns true if the next token is double.
boolean hasNextFloat() Returns true if the next token is float.
boolean hasNext() Returns true if the next token has another token
in its input.
boolean hasNextLine() Returns true if the next token has another line
in its input.
36
Differentiate between Scanner and BufferedReader class.
Scanner class BufferedReader class
It has methods to take input directly in It takes input in string type and then converts
primitive types. them to primitive datatypes.
It is present in java.util package. It is present in java.io package
There's no method to take input in char type. It uses read() method to input character data.

Advantages of using Scanner class are:


1. String handling is easier as each word is obtained as token.
2. It takes input directly of primitive data type.

KEYWORDS

Datatype with only two possible values : boolean


Used for allocating memory to an array : new
Forces early iteration of the loop: continue
Informs that an error has occured in an input-output operation: IOException
Distinguishes between instance variable and class variable: static
Terminates the execution of any loop: break
To create a package: package
Interpreter for java bytecode: JVM
Alternative for large if-else-is statements: switch
Equivalent of else statement: default
To derive a class in java: extends
Used to access the members of the super or the base class: super
To indicate that the method does not return any value: void
To use the classes defined in a package: import
Two print jobs: Printable and Pageable
Class for sending output to printer: Printer class
Access specifier associated with inheritance: protected
To refer to the current object or solve name ambiguity: this
To create an instance of a class: new
Term given to the type of elements in an array: basetype
Default delimiter of the scanner class: whitespace
Class type variables: objects

DIFFERENCES

isUpperCase(char) toUpperCase(char)
It checks if passed argument is uppercase or It converts the passed argument to Uppercase.
not
37
It returns boolean value. It returns char value.
Eg: boolean z= Character.isUpperCase('z'); Eg: char X=Character.toUpperCase('a');
Z=false X='A'

read() readLine()
read() method can read only one byte of data. readLine() method can read more than
Reads data in int type Reads data in String type
Eg: char k=(char)br.read(); Eg: String str=br.readLine();

Ordinary Variable Array Variable


Ordinary variable can store only single value at Array variable can hold more than one value
a time. referred by same name.
Memory for an ordinary variable is allocated Memory for an array is allocated during
during compilation. execution.
Eg: int a=10; Eg: int a[]={1,2,3,4,5};

charAt(int) indexOf(char)
It receives an integer argument and returns the It receives a character argument and returns the
character at that position. position of the first occurrence of the given
character in the String.
Return type is char. Return type is int.
Eg: char k="hello".charAt(2); Eg: int p="hello".indexOf('l');
K='l' p=2

= ==
It is an assignment operator. It is a relational operator.
It assigns the right hand side value to left hand It checks if two values are equal or not and
side variable. returns true or false
Eg: int a=5; Eg: (6= =5) returns false

Math.rint() Math.round()
It truncates the decimal part of the number and It truncates the decimal part of the number and
returns the nearest value in double datatype. returns the nearest value in int type.
double x=Math.rint(15.5); int x=Math.round(15.5);
x=16.0 x=16

break continue return


It forces early termination of It forces early iteration of the It terminates the method and
the loop loop transfers the control to calling
method.
Can be used in loops and Can be used in loops only Can be used in methods
switch statement.

38

You might also like