You are on page 1of 68

Solutions to Chapter One Questions

1. Why is Java known as a platform-neutral language?


Ans.
Java is known as platform-neutral language because Java's bytecodes are designed to be read,
interpreted, and executed in exactly the same manner on any computer hardware or operating system
that supports a Java run-time.
2. How is Java more secure than other languages?
Ans.
One of the potential terrors of the Internet is the possibility of security breaches- viruses that infect
your computer, or hackers who take advantage of a software glitch to invade your personal
cyberspace and make off with confidential information.
Applets, which are Java programs, are automatically downloaded when a Web page is displayed. Java
applets, by default, execute within the Java executing environment and are limited to the environment.
This means, an applet cannot access the local file system or other programs of the system where it
executes. This reduces the chance that simply viewing someone's page might harm your system or
data. No system is absolutely reliable and none will ever be; but Java represents the state-of-the-art in
reducing the chances of a disaster.
3. What is multithreading? How does it improve the performance of Java?
Ans.
In a multithreading environment, a thread is the smallest unit of dispatchable code. This means that a
single program can perform two or more tasks simultaneously. For instance a text editor can format
text at the same time that it is printing.
The benefit of Java's multithreading is that the main loop/polling mechanism is eliminated. One
thread can pause without stopping other parts of the program. For example, the idle time created when
a thread reads data from a network or waits for user input can be utilized elsewhere. When a thread
blocks in a Java program, only the single thread that is blocked pauses. All other threads continue to
run.
4. List at least seven major differences between C and Java.
Ans.
The following are the differences between C and Java:
1 Java does not have a preprocessor, and as such, does not have macros like
#define. Constants can be created by using the final modifier when declaring
class and instance variables.
2 In Java, all methods are tied to classes. Java does not support stand-alone
methods.
3 Java does not include the const keyword as present in C or the ability to pass
by const reference explicitly.
4 In Java strings are implemented as objects and not as an array of null-
terminated characters.
5 Java has some additional primitive data types like byte and Boolean. Data
types in Java have a fixed size regardless of the operating system used.
6 The goto keyword does not exist in Java (it's a reserved word, but currently
unimplemented). You can, however, use labeled breaks and continues to
break out of and continue executing complex switch or loop constructs.
7 Java does not use pointers.
8 In Java, arrays are real objects because you can allocate memory using the
new operator.

5. How is Java strongly associated with the Internet?


Ans.
Internet users can use Java to create applet programs and run them locally using "Java-enabled
browsers" such as HotJava. They can also use a Java-enabled browser to download an applet located
on a computer anywhere in the Internet and run it on their local computer. Internet users can also set
up their websites containing java applets that could be used by other remote users of the Internet.
6. What is Hypertext Markup Language? Describe its role in the implementation of Java applets.
Ans.
Hypertext Markup Language or HTML is a markup language that uses predefined tags to specify the
browser how it needs to display a Web page.
Browsers allow us to retrieve the information from the Internet and display it using the Hypertext
Markup Language (HTML). HotJava, Netscape Navigator and Internet Explorer are some popular
Web browsers. A Web page can embed Java applets. To embed an applet, the <Applet> tag is used in
the HTML document. When a browser encounters the <Applet> tag it loads the applet and executes it
with the browser Java Virtual Machine (JVM).

7. List out primary goals of Java Technology.


Ans.
The primary goals of Java technology are:
1 To provide an easy to use language by avoiding pitfalls of other languages
and enables users to create clear and streamlined code.
2 To provide an interpreted environment for improved speed of development
and code portability.
3 To provide a way for programs to run more than one thread of activity.
4 To furnish better security.

FAQ
1. Why is Java considered ideal for network communication?
Ans:
Java is considered ideal for network communication because it is a platform independent language.
Java enables an application to be executed on any network. The built-in classes of Java support
TCP/IP and UDP protocols used for network communication. Java supports the Client-Server model
for network communication.
2. What is a bytecode?
Ans:
Bytecode is a compiled format of a Java program. Once a Java program is converted into bytecode it
can be transferred across the network and executed by a Java Virtual Machine (JVM).
3. What is an appletviewer?
Ans:
An appletviewer allows you to run an applet without the overhead of running a Web browser.
4. Define Garbage Collection.
Ans:
Garbage Collection is a process that automatically frees the memory of objects that are no longer in
use. There is no specification of a technique for garbage collection. The implementation has been left
to vendors.

Solutions to Chapter Two Questions


1. What is object-oriented programming? How is it different from the procedure-oriented
programming?
Ans.
Object- oriented programming is a method of implementation in which programs are organized as co-
operative collection of objects, each of which represents an instance of some class and whose classes
all members of a hierarchy of classes united in inheritance relationships.
With procedural programming you are able to combine returning sequences of statements into one
single place. A procedure call is used to invoke the procedure. After the sequence is processed, flow
of control proceeds right after the position where the call was made

2. How are data and methods organized in an object-oriented program?


Ans.
In an object-oriented program, a set of variables and functions used to describe an object constitutes a
"class".
A class defines the structure and behavior (data and method) that will be shared by a set of objects.
Each object of a given class contains the structure and behavior defined by the class, as if it were
stamped out of a mould in the shape of a class. A class is a logical construct. An object has physical
reality. When you create a class, you will specify the code and data that will constitute that class.
Collectively, these elements are called the members of the class. Specifically, the data defined by the
class are referred to as member variables or instance variables. The code that operates on that data is
referred to as member methods or just methods, which define the use of the member variables.

3. What are unique advantages of an object-oriented programming paradigm?


Ans.
OOP offers several advantages to both the program designer and the user. The important advantages
are:
1 Reusability: Elimination of redundant code and use of existing classes
through inheritance. Thus provides economy of expression.
2 Modularity: Programs can be the built from standard working modules.
3 Security: Principle of information hiding helps programmer to build secure
programs.
4 Easy mapping: Object in the problem domain can be directly mapped to the
objects in the program.
5 Scalability: Can be easily upgraded from small programs to large programs.
Object-oriented systems are also resilient to change and evolve over time in a
better way.
6 Easy management: Easy management of software complexity.
4. Distinguish between the following terms:
1 Objects and classes
2 Data abstraction and data encapsulation
3 Inheritance and polymorphism
4 Dynamic binding and message passing
Ans.
1 Objects and classes: Object is a physical entity which represents a person,
vehicle or a conceptual entity (thing in existence) like bank account,
company etc.
A set of variables and functions used to describe an object is a "class".
A class defines the structure and behavior (data and code) that will be shared
by a set of objects. Each object of a given class contains the structure and
behavior defined by the class, as if it were stamped out of a mould in the
shape of a class. A class is a logical construct. An object has physical reality.
When you create a class, you will specify the code and data that will
constitute that class. Collectively, these elements are called the members of
the class. Specifically, the data defined by the class are referred to as member
variables or instance variables. The code that operates on that data is referred
to as member methods or just methods, which define the use of the member
variables.
1 Data abstraction and data encapsulation: Abstraction - the act or process
of leaving out of consideration one or more qualities of a complex object so
as to attend to others. Solving a problem with objects requires you to build
the objects tailored to your solution. We choose to ignore its inessential
details, dealing instead with the generalized and idealized model of the
object.
Encapsulation - The ability to provide users with a well-defined interface to a
set of functions in a way, which hides their internal workings. In object-
oriented programming, the technique of keeping together data structures and
the methods (procedures) which act on them. The easiest way to think of
encapsulation is to reference phones. There are many different types of
phones, which consumers can purchase today. All of the phones used today
will communicate with each other through a standard interface. For example,
a phone made by GE can be used to call a phone made by Panasonic.
Although their internal implementation may be different, their public
interface is the same. This is the idea of encapsulation.
1 Inheritance and polymorphism: Inheritance in object-oriented
programming means that a class of objects can inherit properties from
another class of objects. When inheritance occurs, one class is then referred
as the 'parent class' or 'superclass' or 'base class'. In turn, these serve as a
pattern for a 'derived class' or 'subclass'.
Inheritance is an important concept since it allows reuse of class definition
without requiring major code changes. Inheritance can mean just reusing
code, or can mean that you have used a whole class of object with all its
variables and functions.
Polymorphism: It is a key concept in object-oriented programming. Poly
means many, morph means change (or 'form').
Polymorphism is simply a name given to an action that is performed by
similar objects. Polymorphism allows a common data-gathering message to
be sent to each class and allows each subclass object to respond to a message
format in an appropriate manner to its own properties. Polymorphism
encourages something we call 'extendibility'. In other words, an object or a
class can have its uses extended.
1 Dynamic binding and message passing: Dynamic binding in java is the
mechanism by which compiler cannot determine which method
implementation to use in advance. Based on the class of the object, the
runtime system selects the appropriate method at runtime. Dynamic binding
is also needed when the compiler determines that there is more than one
possible method that can be executed by a particular call.
Java's program units, classes, are loaded dynamically (when needed) by the
Java run-time system. Loaded classes are then dynamically linked with
existing classes to form an integrated unit. The lengthy link-and-load step
required by third-generation programming languages is eliminated.
Message Passing: In an object based world the only way for anything to
happen is by objects communicating with each other and acting on the
results. This communication is called message passing and involves one
object sending a message to another and (possibly) receiving a result.
5. Describe inheritance as applied to OOP.
Ans.
Inheritance in object oriented programming means that a class of objects can inherit properties from
another class of objects. When inheritance occurs, one class is then referred to as the 'parent class' or
'superclass' or 'base class'. In turn, these serve as a pattern for a 'derived class' or 'subclass'.
Inheritance is an important concept since it allows reuse of class definition without requiring major
code changes. Inheritance can mean just reusing code, or can mean that you have used a whole class
of object with all its variables and functions.
6. List a few areas of application of OOP technology.
Ans.
OOP can be used for such diverse applications as Real-time systems, simulation and modeling, AI
and Expert systems parallel programming and Neural networks, Decision support systems, Office
automation systems and others.
7. State whether the following statements are TRUE or FALSE:
1 In conventional, procedure-oriented programming, all data are shared by all
functions.
Ans.
True
1 The main emphasis of procedure-oriented programming is on algorithms
rather than on data.
Ans.
True
1 One of the striking features of object-oriented programming is the division of
programs into objects that represent real-world entities.
Ans.
True
1 Wrapping up of data of different types into a single unit is known as
encapsulation.
Ans.
True

1 One problem with OOP is that once a class is created, it can never be
changed.
Ans.
True
1 Inheritance means the ability to reuse the data values of one object by other
objects.
Ans.
True
1 Polymorphism is extensively used in implementing inheritance.
Ans.
False
1 Object-oriented programs are executed much faster than conventional
programs.
Ans.
True
1 Object-oriented systems can scale up better from small to large.
Ans.
True
1 Object-oriented approach cannot be used to create databases.
Ans.
False

FAQ
1. What are the examples of the object-oriented programming languages?
Ans:
The examples of the object-oriented programming languages are: Simula, C++, Python, Smalltalk,
CLOS, and Java.
2. What are the primary object-oriented methodologies used currently?
Ans:
The primary object-oriented methodologies are: BON, FUSION, HOOD, IBM, and UML.
3. How did object-orientation evolve?
Ans:
The object-orientation evolved with the evolution of Simula that provided features, such as objects,
classes, and inheritance. Simula was the first object-oriented programming language. Simula 1 was a
simulation language and Simula 67 was referred to as Simula. Smalltalk was another language having
various features, such as classes, inheritance, and graphical user environment.
4. Class B inherits features from its base class, class A. Class C is a sub class of class B and inherits
features from class B. How many times will the features of class A appear in class C?
Ans:
The following figure shows the class hierarchy for classes A, B, and C:

Class Hierarchy
Class B inherits features from its base class, Class A. These features occur only once in Class B. Class
C inherits features from its base class, Class B. The features inherited by Class C include the features
that Class B inherited from Class A. Therefore, the features of Class A appear only once in Class C.

Solutions to Chapter Three Questions


1. Describe the structure of a typical Java program.
Ans.
A Java program may contain many classes of which only one class defines a main method. Classes
contain data members and methods. Methods of a class operate on the data members of the class.
Methods may contain data type declarations and executable statements. To write a Java program, we
first define classes and then put them together.
A Java program may contain one or more sections as shown in the following figure:
Documentation Section Suggested

Package Statement Optional

Import Statements Optional

Interface Statements Optional

Class Definitions Essential

Main Method class


{
Main Method Definition Essential
}
General Structure Of a Java program
Documentation Section
The documentation section comprises a set of comment lines giving the name of the program, the
author and other details. Java also uses the comment /**...*/ known as documentation comment.

Package Statement
The first statement allowed in a Java file is a package statement. This statement declares a package
name and informs the compiler that the classes defined here belong to this package.
Example: package student;

Import Statement
The next thing after a package statement (but before any class definitions) may be a number of import
statements. This is similar to the #include statement in C++. Example:
import student.test;
This statement instructs the interpreter to load the test class contained in the package student.

Interface Statements
An interface is like a class but includes a group of method declarations. This is also an optional
section and is used only when we wish to implement the multiple inheritance feature in the program.

Class Definitions
A Java program may contain multiple class definitions. Classes are the primary and essential elements
of a Java program.

Main Method Class


Since every Java stand-alone program requires a main method as its starting point, this class is the
essential part of a Java program. A simple Java program may contain only this part. The main method
creates objects of various classes and establishes communications between them.

2. What is the task of the main method in a Java program?


Ans.
After you specify the keywords for declaring the main() method, you specify a String array as
parameter of the main() method. The String array represents command line arguments. It is
compulsory for a user to specify the parameter to the main() method in all Java programs unlike in C
and C++.
For example,
class class1
{
public static void main (String args[])
{
System.out.println("Hello")
}
}

3. What is a token? List the various types of tokens supported by Java.


Ans.
Java Language includes four types of tokens. They are:
1 Reserved Keywords
2 Identifiers
3 Literals
4 Operators

Keywords
Keywords are an essential part of a language definition. They implement specific features of the
language. Java language has reserved 60 words as keywords. The following table lists the keywords.
These keywords have specific meaning in Java, we cannot use them as names for variables, classes,
methods. All keywords are to be written in lower case letters. Since Java is case-sensitive.
The following table lists the Java keywords:
abstract boolean break byte byvalue*
case cast catch char class
const* continue default do double
else extends false** final finally
float for future* generic* goto*
if implements import inner* instanceof
int Interface long native new
null** operator* outer* package private
protected public rest* return short
static super switch synchronizatio this
n
threadsafe* throw throws transient true**
Try var* void volatile while
* Reserved for future use

Identifiers
Identifiers are used for naming classes, methods, variables, objects, labels, package and interfaces in a
program.
Examples:
Average
Sum
Batch_strength

Literals
Literals in Java are a sequence of characters (digits, letters, and other characters) that represent
constant values to be stored in variables. Java language specifies five major types of literals. They are:
1 Integer literals
2 Floating point literals
3 Character literals
4 String literals
5 Boolean literals

Operators
An operator is a symbol that takes one or more operands and operates on them to produce a result.
4. Why can't we use a keyword as a variable name?
Ans.
Keywords are an essential part of a language definition. They implement specific features of the
language. Java language has reserved 60 words as keywords. These keywords have specific meaning
in Java, so you cannot use them as names for variables.
5. Enumerate the rules for creating identifiers in Java.
Ans.
Java identifiers follow the following rules:
1 They can have alphabets, digits, and the underscore and dollar sign
characters.
2 They must not begin with a digit
3 Uppercase and lowercase letters are distinct.
4 They can be of any length.
6. What are the conventions followed in Java for naming identifiers? Give examples.
Ans.
Conventions for naming Java identifiers are:
1 Identifier name has to be meaningful.
2 There should be no embedded space in an identifier name.
For example: studentName, employeeID.
7. Explain the println statement in Java with an example?
Ans.
Consider the following statement:
System.out.println ("string to be printed");
The statement begins with System.out. This is a constant that represents the default output mode,
which in this case is the screen. The constant helps to read and display the data in a Java program.
The output is generated using the built-in println() method. The string that is assigned to the println()
method is displayed when the statement is executed.
For example,
class Class2
{
public static void main (String args[])
{
System.out.println("Here is your string");
}
}
The above program will show the following output:
Here is your string

8. Why is the main() method in Java declared static?


Ans.
The keyword static helps to specify that the main() method can be called without instantiating an
object of a class. This is necessary because the main() method is called by the Java interpreter before
any objects are created.
public static void main (String args[])
{//code}
After specifying the keyword static, you specify the void keyword. This keyword indicates to the
compiler that, the main() method does not return a value.

9. What is an applet?
Ans.
Applets are small Java programs developed for Internet applications. An applet located on a distant
computer (Server) can be downloaded via Internet and executed on a local computer (Client) using a
Java-capable browser.

10. Explain with a simple example how to create, compile and run a program in Java.
Ans.
Java program involves two steps:
1. Compiling source code into bytecode using javac compiler
2. Executing the bytecode program using java interpreter
For example, consider the following program
class ProgramDemo
{
public static void main (String args[])
{
System.out.println("Here is your string");
}
}
First, save the program as ProgramDemo.java. Then, to compile this program type the following
command at command prompt:
C:\Dir1> javac ProgramDemo.java.
Once the program compiles successfully run this program by typing the following command at
command prompt:
C:\Dir1> java ProgramDemo

FAQ
1. Which command can be used to compile a Java program from the command line?
Ans:
The Java compiler javac is used to compile a Java program from the command line. The command to
compile a Java program from the command prompt is:
C:\WORK >javac first.java
In the above statement, C:\ specifies that the command window starts in directory C:\ and
work>first.java specifies that the first.java program is contained in work folder.

2. Is it always necessary to recompile a program after you make a change in the program?
Ans:
Yes, it is necessary that the program must be recompiled each time you make any change in the
program.

3. How can you run a Java program?


Ans:
After compiling the java program, type "java classname" at the command prompt.
4. Class B inherits features from its base class, class A. Class C is a sub class of class B and inherits
features from class B. How many times will the features of class A appear in class C?
Ans:
Once
5. How can you convert an applet to an application?
Ans:
After compiling the java program, type "java classname" at the command prompt. You can convert an
applet to an application by including the main() method in the applet. The declarations included in the
init() method of the applet need to perform in the constructor of the class. The applet class needs to
extend from a frame and size, and visibility of the frame is set in the main() method.

Solutions to Chapter Four Questions


1. What is a constant?
Ans.
Constants are fixed values that do not change during the execution of a program. In Java, you can use
the final keyword to specify that the value of a variable cannot change.
For example,
public static final int x =10;
Here, x is a final variable with value 10.
<A> numeric constants:-<a>integer constants
:-<b> real constant
<B>character constant:-<1>character constants
:-<2> string constant

2. What is a variable?
Ans.
A variable is an identifier that denotes a storage location used to store a data value. Unlike constants
that remain unchanged during the execution of a program, a variable may take different values at
different times during the execution of the program.

3. List the eight basic data types used in Java. Give examples.
Ans.
The eight basic data types used in java are:
byte: It is the smallest integer type. This is a signed 8-bit type and has a range from -128 to 127. For
example, the following declaration declares two variables B and C of type byte.
byte b,c;
b =2;
c = -114;
short: It is a signed 16-bit type and has a range from -32,768 to 32,767. For example, the following
declaration declares variable K of type short.
short k;
k = 2;
int: It is a signed 32-bit type and has a range from -2,147,483,648 to
2,147,483,647.
For example,
int x = 10;
int j = 98;
long: This is signed 64-bit type and has a range from -263 to 263 -1.
For example,
long ds = 1000;
long se;
se =ds * 24 * 60 * 60;
double: It uses 64 bits to store a value.
For example,
double P, R;
P = 10.8;
R =3.14215;
float: It uses 32 bits to store a value.
For example,
float x;
x = -1111;
int : It uses 32 bits to store a value.
For example,
Int score;
Score=90;
char: this data type is used to store characters. It is 16-bit type and has a range
from 0 to 65,536.
For example,
char c1,c2;
c1 =84;
c2 ='g';
boolean: it can have only one of two possible values, true or false.
For example,
boolean flag;
flag= false;

4. What is scope of a variable?


Ans.
The area of the program where the variable is accessible (i.e., usable) is called its scope.
Java variables are actually classified into three kinds:
1 Instance Variables
2 Class variables
3 Local variables
Instance and class variables are declared inside a class. Instance variables are created when the objects
are instantiated and therefore they are associated with the objects. They take different values for each
object. On the other hand, class variables are global to a class and belong to the entire set of objects
that the class creates.
Variables declared and used inside methods are called local variables. They are called so because they
are not available for use outside the method definition. Local variables can also be declared inside
program blocks that are defined between an opening brace '{' and a closing brace '}'. These variables
are visible to the program only from the beginning of its program block to the end of the program
block. When the program control leaves a block, all the variables in the block will cease to exist.

5. What is type casting? Why is it required in programming?


Ans.
The process of converting one data type to another is called casting.
Type variable1 = (type) variable2;
Examples:
int m = 50;
byte n = (byte)m;
long distance = (long)m;
Type casting is required in programming when you want to assign the value of one variable to another
variable of different data type.

6. Which of the following are invalid constants and why?

0.001 5*1.5 RS 75.50

+100 75.42E-2 "15.75"

-45.6 -1.4e(+4) 0.000001234

Ans.
The following are invalid constants:
1 RS 75.50: It should be written as "RS 75.50"
2 -1.4e(+4): It should be written as -1.4e+4

7. Which of the following are invalid variable names and why?

minimum first.Name n1+ n2

doubles 3rd –row N$

float Sum Total Total-Marks

Ans.
The following are invalid variable names:
1 first.Name: Variable name should not have a period in between
2 n1+ n2: Variable name should not have a '+' in between
3 3rd -row: Variable name should not begin with a digit
4 float: Variable name should not be a keyword
5 Sum Total: Variable name should not have an embedded space
6 Total-Marks: Variable name should not have a '-' in between. It can only
have the underscore sign.
8. Find errors, if any, in the following declaration statements:
int x;
float length, height;
double = p,q;
character c1;
final int total;
final pi = 3.142;
long int m;
Ans.
The statements that contain errors are:
double = p,q;
character c1;
final pi = 3.142;
long int m;

9. Write a program to determine the sum of the following harmonic series for a given value of n:
1+1/2 + 1/3+ ..............+1/n
The value of n should be given interactively through the keyboard.
Ans.
public class Series
{
double total;
public void calculate(int n)
{
for(double ctr=1;ctr<=n;ctr++)
{
total=total+1/ctr;
}
System.out.println("Sum of harmonic series: "+total);
}
public static void main(String a[])
{
Series object=new Series();
int num=Integer.parseInt(a[0]);
object.calculate(num);
}
}

10. Write a program to convert the given temperature in Fahrenheit to Celsius using the following
conversion formula
F-32
C = 1.8 and display the values in a tabular form.
Ans.
public class Celsius
{
double celsius;
double fahrenheit;
public Celsius()
{
fahrenheit=98.4;
}
public void convert()
{
celsius=(fahrenheit-32)/1.8;
System.out.println("Temperature in celsius: "+celsius);
}
public static void main(String a[])
{
Celsius object=new Celsius();
object.convert();
}
}

FAQ
1. How can you convert strings to numbers?
Ans:
Strings can be converted into numbers by using the Integer, Float, Double and Long type wrapper
classes.
2. What will happen if the data type of a variable and the value assigned to a variable are different?
Ans:
If the data type of a variable and the value assigned to the variable are different then compilation error
occurs. If an integer variable is assigned a character value, the ASCII value of the assigned character
is displayed as an output. The following code shows assigning a character value to an integer variable.
class datatype{
public static void main(String a[])
{
int x= 'b';
System.out.print(x);
}
}
In the preceding code, the ASCII value of the character b is displayed as 98.
Similarly, if you assign a float or a double value to a character variable, an error message is displayed.
The following code shows assigning a double value to a character variable:
class datatype{
public static void main(String a[])
{
char x= 5.5;
System.out.print(x);
}
}
Java is a strongly typed language and it allows the values of the specific data types, which are
compatible with the type of variable.
3. Why is the data type of the argument that main() method takes?
Ans:
The main() method takes a String as argument.

4. How is memory allocated to arrays in Java?


Ans:
In Java, memory is allocated using the new operator. Consider the following example,
int [] marks;
marks=new int[3];

Solutions to Chapter Five Questions


1. Which of the following arithmetic expressions are valid?

a) 25/3 % 2 e) -14 % 3

b) +9/4 + 5 f) 15.25 + -5.0

c) 7.5 % 3 g) (5/3) * 3 + 5 % 3

d) 14 % 3 + 7 % 2 h) 21 % (int) 4.5

Ans.
All of the above arithmetic expressions are valid.

2. Write Java assignment statements to evaluate the following equations:


a) Area = r2+2 rh
2m1m 2
Torque = *g
b)
m1m 2

c) Side = a 2 + b2 – 2ab cos(x)

 velocity2 
Energy = mass  acceleration * height + 
 2 
d)

Ans.
import java.io.*;
public class AssignmentStatements{
int r, h, m1, m2, a, b, x, mass, acceleration, height, velocity;
double area, torque, side, energy;
public void calculateArea(){
try{
System.out.print("Enter radius : ");
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
r = Integer.parseInt(br.readLine());
System.out.print("Enter height : ");
h = Integer.parseInt(br.readLine());
area = (3.14*r*r)+(2*3.14*r*h);
System.out.println("The area is : " + area);
} catch(Exception e){
System.out.println("Error");
}
}
public void calculateTorque(){
try{
System.out.print("Enter m1 : ");
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
m1 = Integer.parseInt(br.readLine());
System.out.print("Enter m2 : ");
m2 = Integer.parseInt(br.readLine());
torque = ((2*m1*m2)/(m1+m2))*9.8;
System.out.println("The torque is : " + torque);
} catch(Exception e){
System.out.println("Error");
}
}
public void calculateSide(){
try{
System.out.print("Enter a : ");
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
a = Integer.parseInt(br.readLine());
System.out.print("Enter b : ");
b = Integer.parseInt(br.readLine());
System.out.print("Enter x : ");
x = Integer.parseInt(br.readLine());
side = Math.sqrt((a*a) + (b*b) -(2*a*b*Math.cos(x)));
System.out.println("The area is : " + side);
} catch(Exception e){
System.out.println("Errpr");
}
}
public void calculateEnergy(){
try{
System.out.print("Enter mass : ");
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
mass = Integer.parseInt(br.readLine());
System.out.print("Enter acceleration : ");
acceleration = Integer.parseInt(br.readLine());
System.out.print("Enter height : ");
height = Integer.parseInt(br.readLine());
System.out.print("Enter velocity : ");
velocity = Integer.parseInt(br.readLine());
energy = mass*(acceleration*height+((velocity*velocity)/2));
System.out.println("The energy is : " + energy);
} catch(Exception e){
System.out.println("Errpr");
}
}
public static void main(String arg[]){
AssignmentStatements as = new AssignmentStatements();
as.calculateArea();
as.calculateTorque();
as.calculateSide();
as.calculateEnergy();
}
}
3. Identify unnecessary parenthesis in the following arithmetic expressions.
(a) (x-(y/5)+z) % 8) + 25
(b) ((x-y) * p) + q
(c) (m*n) + (-x/y)
(d) x/(3*y)
Ans.
(a) (x-(y/5)+z) % 8) + 25. The parenthesis after 8 in this expression has no opening parenthesis.
(b) ((x-y) * p) + q. It can also be written (x-y)*p +q
(c) (m*n) + (-x/y). It can also be written m*n +-x/y
(d) x/(3*y). No unnecessary parenthesis is there in it.

4 Determine the value of each of the following logical expressions if a=5, b=10 and c=-6
(a) a>b && a<c
Ans. false

(b) a<b && a>c


Ans. true

(c) a==c || b>a


Ans. true

(d) b>15 && c<0 || a>0


Ans. true

(e) (a/2.0 == 0.0 && b/2.0 != 0.0) || c< 0.0


Ans. true

5 The straight-line method of computing the early depreciation of the value of an item is given by
Purchase price − Salvage value
Depreciation =
Years of service
Write a program to determine the salvage value of an item when the purchase price, years of service,
and the annual depreciation are given.
Ans.
class Depreciation
{
double PurchasePrice;
double SalvageValue;
double DepricatValue;
int Years;
public double Salvage(double PurchasePrice, double DepricatValue, int
Years)
{
return PurchasePrice - (DepricatValue * Years);
}
public static void main(String args[])
{
Depreciation dep = new Depreciation ();
System.out.println("The salvage value is: " + dep.Salvage(2000.00,
250.00, 5));
}
}

6. The total distance traveled by a vehicle in t seconds is given by


Distance = ut + (at2)/2
Where u is the initial velocity (metres per second), a is the acceleration (metres per second). Write a
program to evaluate the distance traveled at regular intervals of time, given the values of u and a. The
program should provide the flexibility to the user to select his own time intervals and repeat the
calculations for different values of u and a.
Ans.
import java.io.*;
class Distance{
int a;
int t;
int u;
int dist;
public Distance()
{
a = 10;
u = 10;
}
public void calculate(){
try{
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
System.out.print("Enter time (sec): ");
t = Integer.parseInt(br.readLine());
dist = (u*t) + (a*t*t)/2;
System.out.println("The distance is : " + dist + " meters");
}catch(Exception e){
System.out.println("error");
}
}
public static void main(String arg[]){
Distance d = new Distance();
d.calculate();
}
}

7. In inventory management, the Economic Order Quality for a single item is given by

2* demand rate *setup costs


EOQ =
Holding cost per item per unit time
and the optimal Time Between Orders

2*setup costs
TBO =
demand rate* holding cost per unit time
Write a program to compute EOQ and TBO, given demand rate (items per unit time), setup costs (per
order), and the holding cost (per item per unit time).
Ans.
class InvenManagement
{
int DemandRate;
double SetupCost;
double HoldCost;
public double EOQ(double SetupCost, double HoldCost, int DemandRate)
{
double value = (2*DemandRate*SetupCost)/HoldCost;
return Math.sqrt(value);
}
public double TBO(double SetupCost, double HoldCost, int DemandRate)
{
double value = (2*SetupCost)/(DemandRate*HoldCost);
return Math.sqrt(value);
}
public static void main(String args[])
{
InvenManagement IM = new InvenManagement();
System.out.println("The value of EOQ is: " + IM.EOQ(10000.00,
3000.00, 5));
System.out.println("The value of TBO is: " + IM.TBO(10000.00,
3000.00, 5));

}
}

FAQ
1. What does it mean when we call a method or field "static"?
Ans:
You can instantiate static variables and methods only once per class. They are class variables, not
instance variables. When you change the value of a static variable in an object, the value of that
variable also changes for all instances of that class.

2. Does Java support pointers?


Ans:
No, there are no pointers in Java as it has references, which is an abstract identifier for an object

3. Do all the arithmetic operators have the same precedence in java?


Ans:
No, all the arithmetic operators do not lie at the same level. The two distinct priority levels of
arithmetic operators in Java:
High priority * / %
Low priority + -
4. Can the == operator be used to determine whether two strings have the same value as in name ==
"John"?
Ans:
Yes, the == operator can be used to determine whether two strings have the same value. In Java, you
can also compare two strings using the equals() method.

Solutions to Chapter Six Questions


1. Determine whether the following are true or false.
(a)When if statements are nested, the last else gets associated with the nearest if without an else.
Ans. True
(b)One if can have more than one else clause.
Ans. False

(c) A switch statement can always be replaced by a series of if....else statements


Ans. True
(d) A switch expression can be of any type.
Ans. False
(e) A program stops its execution when a break statement is encountered.
Ans. False
2. In what ways does a switch statement differ from an if statement?
Ans.
An if statement can be used to make decisions based on range of values or conditions, whereas a
switch statement can make decisions based only on a single integer value. Also, the value provided to
each case statement must be unique.
3. Find errors, if any, in each of the following segments;
(a) if (x+y = z && y > 0)
Ans.
This is not a valid expression. x+y =z and y>0 must be enclosed in parenthesis.
(b) if (code>1);
a = b+c
else
a=0
Ans.
It will give an error because of the semicolon present after the if statement.
(c) if (p < 0) || (q < 0)
Ans.
This statement needs to be written as:
if ( (p < 0) || (q < 0))
4. Rewrite each of the following without using compound relations:
(a) if (grade < = 59 && grade >=50)
second = second + 1
Ans.
If (grade < = 59)
{
if (grade> =50)
second = second + 1;
}
(b) if (number > 100 && number < 0)
System.out.print("Out of range");
else
Sum = sum + number;
Ans.
if (number > 100 )
{
if (number < 0 )
System.out.print("Out of range");
}
else
Sum = sum + number;
}

(c) if ((M1>60 && M2>60 || T >200)


y=1;
else
y=0;
Ans.
if(T>200){
y =1;
}
else if(M1>60){
if(M2>60){
y =1;
}
else y =0;
}
5. Write a program to find the number of and sum of all integers greater than 100 and less than 200
that are divisible by 7.
Ans.
public class Divisible
{
int num;
int sum;
public void calculate()
{
sum=0;
System.out.println("Numbers divisible by 7:");
for(num=100;num<200;num++)
{
if(num%7==0)
{
System.out.println(num);
sum=sum+num;
}
}
System.out.println("Sum: "+sum);
}
public static void main(String a[])
{
Divisible obj=new Divisible();
obj.calculate();
}
}

6. Given a list of marks ranging from 0 to 100, write a program to compute and print the number of
students who have obtained marks
(a) in the range 81 to 100,
(b) in the range 61 to 80,
(c) in the range 41 to 60, and
(d) in the range 0 to 40.
The program should use a minimum number of if statements.
Ans.
import java.io.*;
public class StudentMarks
{
int r1=0;
int r2=0;
int r3=0;
int r4=0;
int rn=1;
static BufferedReader br;
public StudentMarks(int num)
{
int arr[]=new int[num];
try
{
for(int i=0;i<arr.length;i++)
{
System.out.println("enter the marks for Roll number"+ rn);
arr[i]=Integer.parseInt(br.readLine());
rn++;
}
for(int j=0;j<arr.length;j++)
{
if(arr[j]>=0 && arr[j]<=40)
{
r1++;
}
else if(arr[j]>40 && arr[j]<=60)
{
r2++;
}
else if(arr[j]>60 && arr[j]<=80)
{
r3++;
}
else if(arr[j]>80 && arr[j]<=100)
{
r4++;
}
}
System.out.println("Students securing marks in the range of 0-40 are\t"+r1);
System.out.println("Sudents securing marks in the range of 40-60 are\t"+r2);
System.out.println("Sudents securing marks in the range of 60-80 are\t"+r3);
System.out.println("Sudents securing marks in the range of 80-100
are\t"+r4);
}//end of try
catch(Exception exp)
{
System.out.println(exp);
}//end of catch

}//end of constructor
public static void main(String args[])
{
try
{
br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the total number of students in the class");
int total_students=Integer.parseInt(br.readLine());
StudentMarks sm=new StudentMarks(total_students);
}//end of try
catch(Exception exp)
{
System.out.println(exp.getMessage());
}//end of catch
}//end of main
}//end of class

7. A cloth showroom has announced the following seasonal discounts on purchase of items:

Discount

Mill Cloth Handloom Items

0-100 - 5.0%

101-200 5.0% 7.5%

201-300 7.5% 10.0%

Above 300 10.0% 15.0%

Ans.
import java.io.*;
class purchase
{
double bill;
String str;
String str_discount="";
public purchase()
{
try
{
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
System.out.println("Enter the amount of Bill: ");
bill=Double.parseDouble(br.readLine());
System.out.println("Enter the types of clothe: ");
str = br.readLine();
if (str.equalsIgnoreCase("handloom"))
{
if(bill >=0 && bill <=100)
{
bill = bill- (bill*5)/100;
str_discount="5 %";
}
if( bill >100 && bill <=200)
{
bill = bill - (bill*7.5)/100;
str_discount="7.5 %";
}
if(bill >200 && bill<=300)
{
bill = bill - (bill*10)/100;
str_discount="10 %";
}
if (bill > 300)
{
bill = bill -
(bill*15)/100;
str_discount="15
%";
}

}
if(str.equalsIgnoreCase("mill"))
{
System.out.println("enter");
if(bill >=0 && bill <=100)
{
bill = bill;
str_discount="0 %";
}
if( bill >100 && bill <=200)
{
bill = bill - (bill*5)/100;
str_discount="5 %";
}
if(bill >200 && bill<=300)
{
bill = bill - (bill*7.5)/100;
str_discount="7.5 %";
}
if (bill > 300)
{
bill = bill - (bill*10)/100;
str_discount="10 %";
}
}
System.out.println("The Discount is: " + str_discount);
System.out.println("The final bill after discount is: " + bill);
}
catch(Exception e)
{
System.out.println("Exception is :"+e);
}
}
public static void main(String args[])
{
purchase pur = new purchase();
}
}

FAQ
1. Can you use a switch statement inside another switch statement?
Ans:
Yes, you can use a switch statement within another switch statement. This is called nested switch.
Each switch statement creates its own block of case statements. Therefore, no conflict occurs between
the case labels of the inner and outer switch statements.
2. Can the value of the expression in a switch statement be a String or a real number?
Ans:
No, the value of the expression in a switch statement cannot be a String or a real number. It has to be
an integer or a character.
3. Can a switch statement have more than one default statement?
Ans:
No, a switch statement can have only one default statement.
4. Is it necessary for an if statement to have an else statement?
Ans:
No. However, an else statement must be preceded by an if statement.

Solutions to Chapter Seven Questions


1. Compare in terms of their functions, the following pairs of statements:
(a) while and do........while.
(b) while and for.
(c) break and continue.
Ans.
(a) The difference between the do-while statement and the while statement is that in the while
statement, the loop body is executed only when the condition stated in the statement is true. In the do-
while loop, the loop body is executed at least once, regardless of the condition evaluating to true or
false. The while loop is also called the top tested loop whereas the do-while loop is also called the
bottom tested loop.
(b) In the for loop, three sections, initialization, test condition and increment/decrement are placed in
the same line whereas in the while loop, all three sections are placed in three different places in a
program. In the for loop, more than one variable can be initialized, tested and incremented at a time.
(c) The continue statement stops the current iteration of a loop and immediately starts the next
iteration of the same loop. When the current iteration of a loop stops, the statements after the continue
statement in the loop are not executed. The break statement immediately terminates the loop,
bypassing the conditional expression and any remaining code in the body of the loop. When a break
statement is encountered inside the loop, the loop is terminated and program control resumes the next
statement following the loop.

2. Write a program to compute the sum of the digits of a given integer number
Ans.
public class Sum
{

int arr[];
int r=0,i=0,sum=0;
public void calculate(int num)
{
arr=new int[5];

while(num%10>0)
{
r=num%10;
arr[i]=r;
i++;
num=num/10;
sum=sum+r;
}
System.out.println("Sum: "+sum);
}
public static void main(String a[])
{
int number=Integer.parseInt(a[0]);
Sum obj=new Sum();
obj.calculate(number);
}
}
3. Given a number, write a program using while loop to reverse the digits of the number.
For examples, the number 12345 should produce an output 54321.
Ans.
public class Reverse
{
int num;
int arr[],arr1[];
int r=0,i=0;
int len=0;
public void calculate(int num)
{
int num1=num;
arr=new int[5];
arr1=new int[5];
while(num1%10>0)
{
r=num1%10;
arr[i]=r;
i++;
num1=num1/10;
}
len=i;
int j,b,k=i;
System.out.print("Reverse Number:");
for (int a=0;k>0;a++,k--)
{
arr1[a]=arr[k-1];
System.out.print(arr[a]);
}
}
public static void main(String arg[])
{
int number=Integer.parseInt(arg[0]);
Reverse obj=new Reverse();
obj.calculate(number);
}
}
4. Analyze each of the program segments that follow and determine how many times the body of each
loop will be executed.
a) x = 5; b) m = 1;
y = 50; do {
while(x <= y) { …………
x = y / x; ……….
……………. m = m + 2;
……………. }while (m < 10)
}
c) int i; d) int m = 10
for (i=0; i<=5; i= i+2/3)
{ int n= 7;
…………. while ( m % n >= 0)
…………. {
} …………..
m = m + 1;
n = n + 2;
………….
}
Ans.
(a) Infinite
(b) Five
(c) Infinite
(d) Infinite
5. What is empty statement? Explain its usefulness.
Ans.
The empty statement consists of a semicolon. The empty statement is used when the statements within
the loop are not executed.

FAQ
1. How does the program stop running if a loop never ends?
Ans:
A program stops running when it enters an infinite loop by pressing the keys Ctrl and C
simultaneously.
2. Why should the value of the variable used in the condition of the while statement be changed in the
loop body?
Ans:
The value of the variable used in the condition of the while statement should be changed in the loop
body. Otherwise, the condition may always remain true and the loop may never terminate.
3. Which loop is also called the top tested loop?
Ans:
while loop.
4. Which element of the for statement is evaluated before each iteration of the for statement?
Ans:
The test condition

Solutions to Chapter Eight Questions


1. What is class? Differentiate between instance and class variables of a Java class.
Ans.
Class is a template that defines a particular type of object. Classes contain all the features of a
particular set of objects. We can use the class definition to create objects of that of class type, that is,
to create objects that incorporate all the features belonging to that class.
Each object of the class will have its own copy of each of the instance variables that appear in the
class definition. Each object will have its own values for each instance variable. The name 'instance
variable' originates from the fact that an object is an 'instance' or an occurrence of a class and the
values stored in the instance variables for the object differentiate the object from others of the same
class type. An instance variable is declared within the class definition in the usual way, with a type
name and a variable name, and can have an initial value specified.
A given class will only have one copy of each of its class variables, and these will be shared between
all the objects of the class. The class variables exist even if no objects of the class have been created.
They belong to the class, and they can be referenced by any object or class, and not just instances of
that class.
2. How do classes help us to organize our programs?
Ans.
In essence a class definition is very simple. There are just two kinds of things that you can include in
a class definition:

Variables
Variables are the data types that store data items that typically differentiate one object of the class
from another. They are also referred to as data members of a class. Every class you write in Java is
generally made up of two components: attributes and behavior. Let's consider an object to define a
motorcycle. Attributes are the individual things that differentiate one object from another and
determine the state, appearance, or other qualities of that object. The attributes of our motorcycle
might include:
1 color: red, green, silver, brown.
2 make: Honda, BMW, Bultaco.
3 engineOn: true, false.
Attributes are defined by variables, in fact, you can consider them because each instance of a class can
have different values for its variables, each variable is called an instance variable.

Methods
These define the operations you can perform for the class--so they determine what you can do to, or
with, objects of the class. Methods typically operate on the fields--the variables of the class. A class's
behavior determines what instances of that class do when asked to by another class or object.
Behavior is the only way that objects can have anything done to them. Our motorcycle class might
well have the following behavior:
Start the engine
Stop the engine
Speed up
Change gear
To define an object's behavior you create methods.
3. What are objects? How are they created from a class?
Ans.
An object in java is a block of memory that contains a space to store all the instance variables. As
with real-world objects, software objects have state and behavior. In programming terms the state of
an object is determined by its data (variables); the behavior by its methods. Thus a software object
combines data and methods into one unit.
Creating an object is referred to as instantiating an object. The creating object to a class is two-step
process:
1. Declare a variable of class type. This variable does not define an object
instead it is a simply a variable that can refer to an object.
2. Physical copy of the object is created and assigned to that variable.
4. How is a method defined?
Ans.
A method is a group of programming language statements that are given a name. A method is
associated with a particular class. The syntax of a method is
modifier(s) return-type method-name (parameter-list) {
statement-list }
5. When do we declare a member of a class static?
Ans.
A member of a class can be created that can be used without referencing to a specific instance. Such a
member is created by preceding its declaration with the keyword static. A member declared as static
can be accessed without referencing to any other objects of class and before creating any objects of its
class. Methods and variables both can be declared as static. The most common example of static
member, main() is declared static as it is called before any objects exist. All instance variables that are
declared as static are global variables.

6. What is a constructor? What are its special properties?


Ans.
The central player in object initialization is the constructor. In Java, constructors are similar to
methods, but they are not methods. Like a method, a constructor has a set of parameters and a body of
code. Unlike methods, however, constructors have no return type. Like methods, you can give access
specifiers to constructors, but unlike methods, constructors with public, protected, or package access
are not inherited by subclasses. (Also, instead of determining the ability to invoke a method, the
access level of a constructor determines the ability to instantiate an object.)
The special properties of a constructor are:
Constructor- names are the same as the name of the class.
Constructor does not specify a return type.
7. How do we invoke a constructor?
Ans.
The name of the constructor needs to be same as the name of class in which the constructor is
declared.
For example, to define a zero-parameter constructor for the Box class, you would write the following:
No return type specified
Constructor name is the same as class name

public Box ( )
{
... }
You can invoke the constructor box() by writing
Box b = new Box();
To create a box instance, you deploy the new keyword with the class name and a pair of parentheses,
as shown in the following expression:
*-- Keyword
*--Class name
new box( )

8. What is inheritance and how does it help us create new classes quickly?
Ans.
Inheritance refers to the properties of a class being available to other classes as well. The original
class is called Base Class and Derived classes are classes created from the existing class (Base Class).
It will have all the features of the Base class. The concept of inheritance is very important in object-
oriented programming languages. It simplifies code writing thus making programs easier to maintain
and debug. It allows reusability of the code
A subclass is defined as follows:
class subclass extends superclass {
Variables declaration;
Methods declaration;
}
The keyword extends signifies that the properties of the superclass are extended to the subclass. The
subclass will now contain its own variables and methods as well those of the superclass. This kind of
situation occurs when we want to add some more properties to existing class without actually
modifying it.

9. Describe different forms of inheritance with examples.


Ans.
The two forms of inheritance are:
1. Single- level inheritance
2. Multiple- level inheritance

Single-Level Inheritance:
In this form of inheritance, there is only one subclass as an extended subclass of the superclass.
A subclass is defined as follows
class subclass extends superclass {
Variables declaration;
Methods declaration;
}
The keyword extends signifies that the properties of superclass are extended to the subclass. The
subclass will now contain its own variables and methods as well those of the superclass. This kind of
situation occurs when we want to add some more properties to existing class without actually
modifying it.
import java.io.*;
//super class declaration
class book {
String name;
int id;
void showsuper( ) {
System.out.println("the id and name of the book is :" +id+ " " +name);
}
}
class book1 extends book {
String author;
void showderived( ) {
System.out.println("the author name is:" +author);
}
}
class simpleinhertence {
public static void main(String args[ ])
{
book superob=new book( );
book1 subobj = new book1( );
superob.id=10;
superob.name="java";
System.out.println("the contents of super object is");
superob.showsuper( );
System.out.println( );
subobj.id=20;
subobj.name="c programming";
subobj.author="Balaguruswamy";
System.out.println("the contents of the subobj:");
subobj.showsuper( );
subobj.showderived( );
}
}
Result:
The contents of super object is
The id and name of the book is: 10 java
The contents of the subobj:
The id and name of the book is : 20 c programming
The autor name is: Swamy

Multiple-Level Inheritance:
In this form of inheritance, subclass is further extended. This means, that there are subclasses of a
subclass.
The general form of class declaration that further inherits the subclass is shown here:
class subclass-name extends superclass-name
{
body of the class
}
class subclass-name1 extends subclass-name
{
body of the class }
For example, the following program shows the multiple inheritance.
import java.io.*;
//super class declaration
class book {
String name;
int id;
void showsuper( ) {
System.out.println("the id and name of the book is :" +id+ " "+name);
}
}
class book1 extends book {
String author;
void showderived( ) {
System.out.println("the author name is:" +author);
}
}
class book2 extends book1 {
void showderived1( ) {
System.out.println("This is multilevel inheritance");
}
}
class simpleinhertence {
public static void main(String args[ ])
{
book superob=new book( );
book1 subobj = new book1( );
book2 subobj1 = new book2( );
superob.id=10;
superob.name="java";
System.out.println("the contents of super object is");
superob.showsuper( );
System.out.println( );
subobj.id=20;
subobj.name="c programming";
subobj.author="Balaguruswamy";
System.out.println("the contents of the subobj:");
subobj.showsuper( );
subobj.showderived( );
subobj1.showdeived1(); }}
10. Design a class to represent a bank account. Include the following member:
Data members
Name of the depositor
Account Number
Type of account
Balance amount in the account
Methods
To assign initial values
To deposit an amount
To withdraw an amount after checking balance
To display the name and balance
Ans.
import java.io.*;
public class Bank
{
String name;
String accNo;
String accType;
double balance=0;
String amount;
public void input()
{
try{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the Name of a Account Holder");
name=br.readLine();
System.out.println("Enter the Account Number of a Account Holder");
accNo=br.readLine();
System.out.println("Enter the Account Type of a Account Holder");
accType=br.readLine();
System.out.println("Enter the Amount to be deposited");
amount=br.readLine();
double balance=Double.parseDouble(amount);
}
catch(IOException g){}
}
public void deposit()
{
try{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the Amount to be deposited");
amount=br.readLine();
double amt=Double.parseDouble(amount);
balance=balance+amt;
System.out.println("Balance: "+balance);
}
catch(IOException e){}
}
public void withdraw()
{
try{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the Amount to be withdrawl");
amount=br.readLine();
double amt=Double.parseDouble(amount);
balance=balance-amt;
System.out.println("Balance: "+balance);
}
catch(IOException e){}
}
public void display()
{
System.out.println("Account Holder Details");
System.out.println("----------------------");
System.out.println("Name: "+name);
System.out.println("Balance: "+balance);
}
public static void main(String a[])
{
Bank object=new Bank();
while(true)
{
System.out.println("Menu");
System.out.println("1. Enter Details");
System.out.println("2. Deposit Amount");
System.out.println("3. Withdraw Amount");
System.out.println("4. Exit");
try{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the Amount to be withdrawl");
char ch=(char)br.read();
switch(ch)
{
case '1':
object.input();
break;
case '2':
object.deposit();
break;
case '3':
object.withdraw();
break;
case '4':
System.exit(0);
}
}
catch(IOException e){}
}
}
}
11. Assume that a bank maintains two kinds of account for its customers, one called savings account
and the other current account. The savings account provides compound interest and withdrawal
facilities but no cheque book facility. The current account provides cheque book facility but no
interest. Current account holders should also maintain a minimum balance and if the balance falls
below this level, a service charge is imposed.
Create a class Account that stores customer name, account number and the type of account. From this
derive the classes Curr-acct and Sav-acct to make them more specific to their requirements. Include
the necessary methods in order to achieve the following tasks:
Ans.
import java.io.*;
class Account{
String custName;
String accNo;
String amount;
double balance;
public void input(){
try{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the Name of a Account Holder");
custName=br.readLine();
System.out.println("Enter the Account Number of a Account Holder");
accNo=br.readLine();
System.out.println("Enter the Amount to be deposited");
amount=br.readLine();
balance=Double.parseDouble(amount);
}catch(Exception g){}
}
public void deposit(){
try{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the Amount to be deposited");
amount=br.readLine();
double amt=Double.parseDouble(amount);
balance=balance+amt;
System.out.println("Balance: "+balance);
}catch(IOException e){}
}
public void withdraw() {
try{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the Amount to be withdrawl");
amount=br.readLine();
double amt=Double.parseDouble(amount);
balance=balance-amt;
System.out.println("Balance: "+balance);
}catch(IOException e){}
}
public void display(){
System.out.println("Account Holder Details");
System.out.println("----------------------");
System.out.println("Name: "+custName);
System.out.println("Balance: "+balance);
}
}
class Current extends Account{
public void chequebook(){
if(balance<1000)
System.out.println("Cheque book has not been issued");
else
System.out.println("Cheque book has been issued");
}
public void minimumBal(){
double penalty=1000;
if(balance < 10000){
balance=balance-penalty;
}
}
public void display(){
minimumBal();
super.display();
}
}
public class Saving extends Account{
public void calInterest(){
double interest=0;
System.out.println(interest);
balance=balance*Math.pow(1.05, 2);
System.out.println(balance);
}
public void display(){
calInterest();
System.out.println(balance);
super.display();
}
public char menu(){
char choice='a';
System.out.println("Menu");
System.out.println("1. Current Account");
System.out.println("2. Savings Account");
System.out.println("3. Exit");
System.out.println("Enter your choice(1-3)");
try{
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
choice=(char)br.read();
}catch(Exception e){
System.out.println("Error");
}
if (choice =='3'){ System.exit(0);}
return choice;
}
public static void main(String a[]){
char choice;
Saving o=new Saving();
while(true){
choice = o.menu();
try{
switch(choice){
case '1':
Current object=new Current();
while(true){
System.out.println("Menu");
System.out.println("1. Enter Details");
System.out.println("2. Deposit Amount");
System.out.println("3. Withdraw Amount");
System.out.println("4. Display Balance");
System.out.println("5. Issue ChequeBook");
System.out.println("6. Exit");
try{
System.out.println("Enter your choice(1-6)");
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

char ch=(char)br.read();
switch(ch){
case '1':
object.input();
break;
case '2':
object.deposit();
break;
case '3':
object.withdraw();
break;
case '4':
object.display();
break;
case '5':
object.chequebook();
break;
case '6':
choice = o.menu();
default:
System.out.println("Please Enter the valid choice");
break;
}
}catch(IOException e){}
}
case '2':
Saving object1=new Saving();
while(true){
System.out.println("Menu");
System.out.println("1. Enter Details");
System.out.println("2. Deposit Amount");
System.out.println("3. Withdraw Amount");
System.out.println("4. Display Balance");
System.out.println("5. Exit");
try{
System.out.println("Enter your choice(1-4)");
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
char ch=(char)br.read();
switch(ch){
case '1':
object1.input();
break;
case '2':
object1.deposit();
break;
case '3':
object1.withdraw();
break;
case '4':
object1.display();
break;
case '5':
o.menu();
default:
System.out.println("Please enter the valid choice");
break;
}
} catch(Exception e){}
}
case '3':
// System.out.println("Please enter the valid choice");
System.exit(0);
break;
} //switch
}
catch(Exception e){}
} //while
} //main
}

FAQ
1. Can null be called an object?
Ans:
No. A method is not called on a null. For example, y.p() will give an error if y is null and p is a non-
static method.
2. What is the difference between instance creation and class initialization?
Ans:
When you call a constructor with new, an instance is created and when a class is used actively, then
class initialization occurs.
3. Can a subclass access the variable that is declared private in its superclass?
Ans:
Any class member that is declared private is not accessible outside the class where it is declared. Even
a subclass cannot access the private members of its superclass.
4. In what order are the constructors called when a class hierarchy is created?
Ans:
In a class hierarchy constructors are called from superclass to subclass, that is, in the
order of derivation of the classes that make up the hierarchy

Solutions to Chapter Nine Questions


1. What is an array?
Ans.
An array is a sequence of logically related data items. It is a kind of row made of boxes, with each
box holding a value. The number associated with each box is the index of the item. Each box can be
accessed by, first box, second box, third box, and so on, till the nth box. The first box, or the lowest
bound of an array is always zero, which means, the first item in an array is always at position zero of
that array. Position in an array is called index. So the third item in an array would be at index 2 (0,
1,2).

2. Why are arrays easier to use compared to a bunch of related variables?


Ans.
An array is a sequence of logically related data items. It is a kind of row made of boxes, with each
box holding a value.
Arrays have following advantages over bunch of related variables:
1 Arrays of any type can be created. They can have one or more dimensions.
2 Any specific element can be indexed in an array by its index.
3 All like type variables in an array can be referred by a common name.

3. Write a statement to declare and instantiate an array to hold marks obtained by students in different
subjects in a class. Assume that there are up to 60 students in a class and there are 8 subjects.
Ans.
int marks[][]=new int[60][8]

4. Find errors, if any, in the following code segments:


int m;
int x[ ] =int [10];
int [ ] y =int [11];
for (m=1;m<=10; ++m)
x[m]=y[m]=m;
x=y=new int[20];
for (m=0; m<10; ++m)
System.out.println(x[m])
Ans.
The errors in the above statements are mentioned as comments as follows:
int m;
int x[ ] =int [10]; //array created without using new keyword
int [ ] y =int [11]; // array created without using new keyword
for (m=1;m<=10; ++m)
x[m]=y[m]=m; //array can not be assigned values before they are created.
x=y=new int[20];
for (m=0; m<10; ++m)
System.out.println(x[m])

5. An election is contested by 5 candidates. The candidates are numbered 1 to 5 and the voting is done
by marking the candidate number on the ballot paper. Write a program to read the ballots and count
the votes cast for each candidate using an array variable count. In case, a number read is outside the
range 1 to 5, the ballot should be considered as a 'spoilt ballot' and the program should also count the
number of spoilt ballots.
Ans.
import java.io.*;
public class Election
{ int count, i, candidate1, candidate2, candidate3, candidate4, candidate5, spoilt;
public Election(){
count = 0;
i = 0;
candidate1 = 0;
candidate2 = 0;
candidate3 = 0;
candidate4 = 0;
candidate5 = 0;
spoilt = 0;
}
public void electionCount(){
while(true){
try{
System.out.println("Enter integer between 1 to 5 to vote a candidate");
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
i = Integer.parseInt(br.readLine());
if ((i>5)||(i<1)){
System.out.println("Enter a valid vote id between 1 to 5");
spoilt++;
count++;
}else if(i==1){
candidate1++;
count++;
}else if(i==2){
candidate2++;
count++;
}else if(i==3){
candidate3++;
count++;
}else if(i==4){
candidate4++;
count++;
}else if(i==5){
candidate5++;
count++;
}
System.out.println("Spoilt = "+spoilt);
System.out.println("Candidate1 = "+candidate1);
System.out.println("Candidate2 = "+candidate2);
System.out.println("Candidate3 = "+candidate3);
System.out.println("Candidate4 = "+candidate4);
System.out.println("Candidate5 = "+candidate5);
System.out.println("Total : "+count);
System.out.println("Do you want to continue(y/n): ");
char ch = (char)br.read();
if(ch == 'n'||ch == 'N') break;
}catch(Exception e){System.out.println("Error");}
}
}
public static void main(String arg[]){
Election e = new Election();
e.electionCount();
}
}

6. Two matrices that have the same number of rows and columns can be multiplied to produce a third
matrix. Consider the following two matrices.
a11 a12 ............. a 1n   b 11 b 12 ............. b1n 
A = a 21 a 22 ............. a 2n  B =  b 21 b 22 ......... .... b2n
 
a n1 a n2 ............. a nm  b n1 b n2 ............. bnm

The product of A and B is a third matrix C of size b by n where each element of C is given by the
following equation.
n
Cij = ∑ a 1k b kj
k =1

7. Write a program that will read the values of elements of A and B and produce the product matrix C.
Ans.
import java.io.*;
class MatrixMult
{
int m=0;
int n=0;
int a[][]=new int[3][3];
int b[][]=new int[3][3];
int i=0;
int j=0;
int k=0;
int term;
public MatrixMult()
{
try
{

BufferedReader br=new BufferedReader(new


InputStreamReader(System.in));
System.out.print("Enter the value of m and n for a matrix: \n");
System.out.print("\nm: ");
int m =Integer.parseInt(br.readLine());
System.out.print("\nn: ");
int n =Integer.parseInt(br.readLine());
System.out.print("\nEnter first matrix elements(mxn)\n");

/* Input the first matrix */


for(i=0;i<m;i++)
{
System.out.print("\nEnter the row numbers:\n");
for(j=0;j<n;j++)
a[i][j] = Integer.parseInt(br.readLine());
}
System.out.print("\nEnter second matrix elements(nxm)\n");
/* Input the second matrix */
for(j=0;j<n;j++)
{
System.out.print("\nEnter the row numbers:\n");
for(k=0;k<m;k++)
b[j][k] = Integer.parseInt(br.readLine());
}
/* Multiplication of two matrices */
System.out.print("\nMultiplication of the two matrix is:
\n\n");
term = 0;
for(i=0;i<m;i++)
{
for(k=0;k<m;k++)
{
term=0;
for(j=0;j<n;j++)
{
term = term + (a[i][j]*b[j][k]); // multiplication
}
System.out.print("\t");
System.out.print(term);
System.out.print(" ");
}
System.out.print("\n");
}
}catch(Exception e)
{
System.out.println("Exception is :"+e);
}
}
public static void main(String args[])
{
MatrixMult MM = new MatrixMult();
}
}

8. How does String class differ from the StringBuffer class?


Ans.
String class has a limit while there is no limit in StringBuffer class. In the StringBuffer class input is
flushed while it is not so in the String class.
String is an array whose all elements are of character type. String class is used in the same manner
that we might use any other predefined class. For example we might declare an instance of the String
class as follows:
String name = new String();

9. Explain about:
i) Comparison of two strings
ii) Concatenation of two strings

Ans.
i) Comparison of two strings
To compare two strings for equality, use equals(). It has the general form:
boolean equals(object str);
Here, str is the string object being compared with the invoking String object.
It returns true if the string contains the same characters in the same order
compareTo( )
Often, it is not enough to simply know whether two strings are identical.
For sorting applications, we need to know which is less than, equal to, or greater than the next. The
compareTo( ) method of the String class serves this purpose. It has the general form of
compareTo(String str).

Value Meaning

value less than zero the invoking string is less than str

greater than zero the invoking string is greater than str

Zero the two string are equal

Class EqualsDemo {
public static void main(String args[ ]) {
String s1="Hello";
String s2="Hello";
String s3="bye";
System.out.println("COMPARE STRINGS");
// The compareTo method
System.out.println(s1 + "equals" + s2 + "->" + s1.eqals(s2));
System.out.println(s1 + "equals" + s3 + "->" + s1.eqals(s3));
// Using the compareTo method within an if-else statement
if (name1.compareTo(name2)==0) System.out.println("the same");
else System.out.println("not the same");
} }

ii) Concatenation of two strings


String manipulation is something we do quite often in our applications. One of the simplest methods
to concatenate two Strings is by using the '+' operator. To append String s2 to s1 we simply use:
s1 += s2
But Java provides more ways for concatenating Strings. The String class contains a instance method
named concat(String s). To add a new String to a existing String we would code something like this:
s1.concat(s2);
public class Test {
public static void main(String arg[ ]) {
// defining two strings and printing them out
String s1 = new String("sachin");
String s2 = new String("tendulkar");
System.out.println("First String: " + s1);
System.out.println("Second String: " + s2);
// adding the second string to the first and printing result
s1 = s1.concat(s2);
System.out.println("Concatenated: " + s1);
}
}
Output:
First String: Sachin
Second String: Tendulkar
Concatenated: Sachin Tendulkar

9. Explain the methods:


i) trim
ii) substring
iii) length
Ans.
i) trim
The trim method returns a copy of the invoking string from which any leading
and trailing white space has been removed. It has the general form
String trim ( );
class altStr{
public static void main (String args[ ]) {
String str = "Hello";
String str2 = "Java";
str = str.toUpperCase();
str2 = str2.toLowerCase();
System.out.println (str); // HELLO
System.out.println (str2);// java
str = str.concat(str2); // str now equals "HELLO java"
System.out.println (str);
str = str.trim(); // str now equals "HELLOjava"
System.out.println (str);
str = str.substring (5,str.length()); // str = "java"
System.out.println (str);
str = str.replace ('a', 'i'); // str = "jivi"
System.out.println (str);
}
}

ii) substring
The subString method is used to create new instances of the class String from existing instances. The
new string is specified by giving the required index range within the existing string.
String substring(int startIndex)
This returns the sub string that starts at startIndex and runs to the end of the invoking string.
String substring(int start Index, int endIndex)
This returns the substring that starts at startindex and runs through endIndex-1;

iii) length
The length of a string is the number of characters that it contains. To obtain this value call a length
method.
int length();
class strCmp {
public static void main (String args[ ]) {
String str = "Hello";
String str2 = "Java";
System.out.println (str.equals(str2)); // false
System.out.println (str.compareTo(str2)); // a negative number,
i.e. str is less than str2
System.out.println (str.charAt(0)); // H, i.e. char is position 0
System.out.println (str.length() + str2.length()); // 5 + 4 = 9
}
}

FAQ
1. Why arrays as an object are not invoked using method sign() such as myArray.length()?
Ans:
Arrays, like classes, are object references but they do not contain methods. Instead, you can use
myArray.length. In this, the data item (not method) called "length" which belongs to myarray.

2. Can a String object be changed once it has been created?


Ans:
A String object cannot be changed after creation. It means you cannot change the characters that
comprise the String after the String object is created.

3. What is the difference between equals() and ==?


Ans:
The equals() method compares the characters that are inside a String object while == operator
compares whether two object references refer to the same instance.

4. Do all arguments sent to a Java application have to be strings?


Ans:
Yes, all the arguments sent to a Java application have to be string. If you use some other data type,
such as int, you need to convert the value to string.

5. Can you add the numeric value of one string to the value of another if the + operator is used with
strings to link up two different strings?
Ans:
Yes, you can use the value of a String variable as an integer only by using a method that converts the
value of the string variable into a numeric form. This is known as type casting because it casts one
data type, such as a string into another data type, such as int.

Solutions to Chapter Ten Questions


1. What is a Thread?
Ans.
In a thread based multitasking environment, thread is the smallest unit of dispatchable code. A Thread
is a single stream of execution within a process. This means that a single program can perform two or
more tasks simultaneously. For instance a text editor can format text at the same time that it is
printing.

2. Distinguish between Multiprocessing and Multithreading.


Ans.
Multiprocessing: Refers to a computer system's ability to support more than one process (program) at
the same time. Multiprocessing operating systems enable several programs to run concurrently
Multiprocessing systems are much more complicated than single-process systems because the
operating system must allocate resources to competing processes in a reasonable manner.
Multithreading : The ability of an operating system to execute different parts of a program, called
threads, simultaneously. The programmer must carefully design the program in such a way that all the
threads can run at the same time without interfering with each other.

3. Describe the life cycle of a Thread?


Ans.
Thread exists in several states. A thread that has been just created is in the born state. The thread
remains in this state until the thread's start method is called. This causes the thread to enter the
runnable (ready) state when the system assigns a processor to the thread. A thread enters the dead
state when its run method completes or terminates for any reason. When a sleep method is called in a
running thread, that thread becomes ready after the designated sleep time expires. Even if a processor
is available, sleeping thread cannot use it.
A running thread can enter a blocked state. One common way is when thread issues an input/output
request. In this case, a blocked thread becomes ready when the I/O it is waiting for completes.
When a running thread calls wait, the thread enters a waiting state for the particular object on which
'wait' was called. A thread in the 'waiting' state for a particular object becomes ready on a call to
'notify' issued by another thread associated with that object.
A thread enters the 'dead' state when its 'run' method is either completed or throws an uncaught
exception.

4. What is Synchronization? Why do we use it?


Ans.
Multithreading introduces a synchronous behavior in programs. There is a need to enforce
synchronicity when it is necessary. For example, if two threads are to communicate and share a data
structure, there is a need to avoid conflict between them. That is, a thread must be prevented from
writing data while the other thread is reading the data.
To overcome this problem, Java implements a model of interprocess communication called monitor.
The monitor is a control mechanism that can hold only one thread at a time. Once a thread enters a
monitor, all other threads have to wait until that exits from the monitor.

5. How is a thread created?


Ans.
Threads are implemented in the form of objects that contain a method called run( ). The run() method
makes up the entire body of the thread. A typical run( ) would appear as follows:
public void run() {
----------------
--------------- (Statements for implementing thread)
---------------
}
The run() method should be invoked by an object at the concerned thread.
A new thread can be created in two ways:
1 Define a class that implements Runnable interface.
2 Define a class that extends Thread class.

FAQ
1. How does a preemptive scheduler differ from a non-preemptive scheduler?
Ans:
When the time slice of a thread runs out preemptive scheduler interrupts it while the non-preemptive
scheduler waits for the thread to yield control itself.

2. How can one thread wait for another thread to finish before continuing?
Ans:
A thread can wait for another thread to finish before continuing by calling its join() method

3. The two approaches to create threads are by implementing the Runnable interface and by extending
the Thread class. Which of these two approaches is better and why?
Ans:
The Thread class defines the various methods that can be overridden by a derived class. It is advisable
to extend a class when it is being enhanced or modified in some way. If you are not overriding any of
the methods of the Thread class other than the run() method, then it is recommended to implement the
Runnable interface.
In addition, Java does not support multiple inheritance. Applets extend from the Applet class. You
cannot inherit from both the Applet and Thread class. The Runnable interface consists only of the
run() method, which is executed when the thread is activated. You can extend from the Applet class,
implement the Runnable interface and code the run() method. Therefore, when a program needs to
inherit from a class apart from the Thread class, you need to implement the Runnable interface.

4. Which interface is implemented to create threads?


Ans:
The Runnable interface is implemented to create a thread. The Runnable interface contains the run()
method, which is needed to start a thread.

5. How do you ensure that your threads share the processor of the computer properly?
Ans:
To ensure that all the threads share the memory of the processor properly, call the yield() or sleep()
method in the thread. The sleep() method is used to keep the thread in the sleeping mode for a
specified time. The yield() method is used to allocate processor time to a low priority thread.

Solutions to Chapter Eleven Questions


1. What is a package?
Ans.
Packages are containers for classes that can be shared by Java programs. Packages are stored in a
hierarchical manner and are explicitly imported into new class definitions.
Packages are Java's way of grouping a variety of classes and/or interfaces together. The grouping is
done according to functionality. By organizing the classes into packages, we get the following
benefits:
1 Classes contained in packages of other programs can be reused.
2 Two classes in two different packages can have the same name.
3 Packages provide a way to hide classes.
4 Designing is separated from coding by the use of packages.
2. Write a procedure to create your own package.
Ans.
The procedure to create you own package is:
1 Declare the package at the beginning of a file using the package keyword.
package <package_name>
1 Define the class that is to be put into the package and declare it public.
2 Create the subdirectory under the directory where the main source file is
stored.
3 Store the listing as the class_name.java file in the subdirectory.

3. Define interface. How can multiple inheritance be implemented using interfaces?


Ans.
Interfaces are syntactically similar to classes but they lack instance variables, and their methods are
without any body. Once an interface is defined, any number of classes can implement it.
An interface only defines a method's name, return type, and arguments. It does not include executable
code. An interface is defined using the interface keyword.
Java does not support multiple inheritance. This means that classes in Java cannot have more than one
superclass. However, there could be a situation where a class needs to inherit from more than one
class. In such a situation you use interfaces. One class can implement any number of interfaces.

FAQ
1. Is it always necessary that a package statement must be the first statement in a java program?
Ans:
The package statement if present in a Java program must be the first statement. All other statements in
the program must follow the package statement.

2. Why does * show in the following statement?


import java.io. *;
Ans:
The * in the above statement shows that the compiler shall import the entire java.io package. All
classes and interfaces contained in this package will be accessible to you.

3. How do you add a class or an interface to a package?


Ans:
To add a class or an interface to a package, place the package keyword at the top of the source code of
the class or the interface. The package keyword is followed by the name of the package to which the
class or interface is to be added.
4. Compare package with header files.
Ans:
Packages are similar to header files. One difference is that a package contains only classes whereas a
header file can contain independent methods.

Solutions to Chapter Twelve Questions


1. What is an exception?
Ans.
An exception is a run time error. Most of the computer languages do not support exception handling.
Errors must be checked and handled manually. This is cumbersome and troublesome. Java provides
the facility of exception handling and avoids the above problems. By this run time error management
becomes easy.
A Java exception is an object that describes an error condition that has occurred in a piece of code.
When an error or an exceptional condition arises, an object representing that exception is created and
is 'thrown' in the method that caused the error. The method may handle the exception itself or pass it
on. In this way, the exception is caught and processed. Exceptions thrown by Java relate to
fundamental errors that violate the rules of the language.
2. How do we define a try block?
Ans.
The programmer encloses in a try block the code that may generate an exception. The try block is
immediately followed by zero or more catch blocks. Each catch block specifies the type of exception
it can catch and contains an exception handler.
When an exception is thrown, program control leaves the try block and catch blocks are searched for
an appropriate handler.
For example, the following code defines a try block.
try { // monitor a block of code
d=0;
a=42/d;
System.out.println(*This will not be printed,*);
}
3. How do we define a catch block?
Ans.
The 'try' block is immediately followed by zero or more catch blocks. Each catch block specifies the
type of exception it can catch and contains an exception handler.
When an exception is thrown, program control leaves the try block and catch blocks are searched for
an appropriate handler.
For example, the following code defines a try-catch block.
try { // monitor a block of code
d=0;
a=42/d;
System.out.println(*This will not be printed,*);
}
catch(ArithmeticException e)
{
System.out.println("Division by zero");
}

4. How many catch blocks can we use with one try block?
Ans.
The try block is immediately followed by zero or more catch blocks. It means you can use as many
catch blocks with one try block. But there must be at least one catch block following a try block,
unless you are using a finally block.
For example, consider the following program:
Class Exception {
Public Static void main(string args[ ] ){
int d,a;
try { // monitor a block of code
d=0;
a=42/d;
System.out.println(*This will not be printed,*);
} catch(Arithmetic Exception) { // Catch divide-by-zero
error System.out.println(*Division by Zero*);
}
System.out.println(*After catch statement.*);
} }
This program generates the following output
Division by Zero.
After Catch Statement.
5. What is a finally block? When and how is it used? Give a suitable example.
Ans.
After the last catch block, an optional finally block provides code that always executes regardless of
whether or not an exception occurs. If there are no catch blocks following a try block, the finally
block is required.
If a finally block appears after the last catch block, it is executed regardless of whether or not an
exception is thrown.
For example, the following program shows the use of a finally block.
class finaldemo
{
static void A()
{
try
{
System.out.println( "now in A");
throw new RuntimeException("demo");
}
finally
{
System.out.println("finalA");
}
}
public static void main(String args[])
{
try
{
A();
}
catch( Exception e)
{
System.out.println("exc caught");
}
}
}

FAQ
1. Can you have a try block without a catch block?
Ans:
Yes, if there is a finally block accompanying it. A try block needs to be followed by at least a catch or
a finally block.
2. Can there be more than one catch block per try block for the same exception?
Ans:
No. In one program, there can be only one catch block per try block for a single exception. You
cannot use two catch blocks to catch a single exception. For example, there cannot be two catch
blocks both catching a java.lang.ArithmeticException thrown in the try block.
3. Do you have to catch all types of exceptions that might be thrown by Java?
Ans:
Yes, you have to catch all types of exceptions that are thrown in a Java application using the
Exception class.
4. Can you create your own exception classes?
Ans:
Yes, you can create your own exception classes to address application specific constraints. You can
create exception classes by extending the Exception class.
Example
Class invalidAgeException extends Exception

Solutions to Chapter Thirteen Questions


1. What is a file? Why do we require files to store data?
Ans.
File is a collection of information, such as text, data or images saved on a storage device such as a
disk or hard drive. Output from a program may go to screen or the printer, which will not be
permanently stored. In order to store the data permanently we require files to store the data.

2. What is a stream? How is the concept of streams used in Java?


Ans.
A stream in Java is a path along which data flows (like a river or a pipe along which water flows). It
has a source (of data) and a destination (for that data). Both the source and the destination may be
physical devices or programs or other streams in the same program.
Java uses the concept of streams to represent the ordered sequence of data, a common characteristic
shared by all the input/output devices as stated above. A stream presents a uniform, easy-to-use,
object-oriented interface between the program and the input/output devices.

3. What are input and output streams? Explain them with illustrations.
Ans.
As you know, all Java programs automatically import the java.lang package. This package defines a
class called System, which encapsulates several aspects of the run-time environment.
System.out refers to the standard output stream. By default, this is the console. System.in refers to
standard input, which is the keyboard by default. System.err refers to the standard error stream, which
also is the console by default. However, these streams may be redirected to any compatible I/O
device.
System.in is an object of type InputStream; System.out and System.err are objects of type
PrintStream. These are byte streams, even though they typically are used to read and write characters
from and to the console. As you will see, you can wrap these within character-based streams, if
desired.
4. What is a stream class? How are the stream classes classified?
Ans.
The java.io package contains a large number of stream classes that provide capabilities for processing
all types of data. These classes may be categorized into two groups based on the data type on which
they operate.
1 Byte stream classes that provide support for handling I/O operations on bytes.
2 Character stream classes that provide support for managing I/O operations on
characters.
These two groups may further be classified based on their purpose. Byte stream and character stream
classes contain specialized classes to deal with input and output operations independently on various
types of devices. We can also cross-group the streams based on the type of source or destination they
read from or write to. The source (or destination) may be memory, a file or pipe.
FAQ
1. What is a stream?
Ans:
In Java, streams represent the ordered sequence of data. Streams in Java present a uniform, easy- to-
use, object-oriented interface between the program and the input/output devices.

2. What are the return types of the read() methods?


Ans:
There are several overloaded read methods to read bytes and array of bytes from the input stream. The
read() method returns the value of the byte of data it encounters in the input stream as an integer.
When the method encounters the end of the stream, it returns -1.
3. How do two classes in an application communicate with each other using the input stream and the
output stream?
Ans:
Two classes in an application can communicate with each other by using input and output stream.
You can use the following code to allow communication between the Producer and Consumer class:
//Producer.java
import java.io.*;
public class Producer
{
Producer()
{
byte buffer[]=new byte[100]; //allocates 100 bytes to buffer
try
{
System.in.read(buffer,0,100); //reads 100 bytes into buffer
}
catch(IOException ioe)
{
System.out.println("Exception: "+ioe.toString());
}
try
{
FileOutputStream fout=new
FileOutputStream("message.txt");
//opens a file for output
System.out.println("Producer class writing message to the file
message.txt ......");
System.out.println(".");
System.out.println(".");
fout.write(buffer); //writes buffer to the output file
}
catch(FileNotFoundException fnfe)
{
System.out.println("Exception: "+fnfe.toString());
}
catch(IOException ioe)
{
System.out.println("Exception: "+ioe.toString());
}
}
} //end of Producer class

//Consumer.java
import java.io.*;
public class Consumer
{
Consumer()
{
byte buffer[]=new byte[100]; //allocates a buffer of 100 bytes
try
{
FileInputStream file=new FileInputStream("message.txt");
//opens file for input
file.read(buffer,0,50); //reads 50 bytes from start of file
}
catch(Exception e)
{
System.out.println("Exception: "+e.toString());
}
String str=new String(buffer); //initializes String str from buffer
System.out.println("Consumer class reading message from the file
message.txt ......");
System.out.println(str);
}
} //End of Consumer class
//Communicate.java
class Communicate
{
public static void main(String args[])
{
Producer prod = new Producer();
Consumer cons = new Consumer();
}
}//End of Communicate Application
In the preceding code, two classes Producer and Consumer are defined and their objects are
constructed in the Communicate application. The Producer class uses the FileOutputStream class to
write messages to a message.txt file. The consumer class uses the FileInputStream class to read
messages from the message.txt file. Therefore, the two classes communicate by writing and reading
messages to a common file.

4. Do you need to close the Reader stream explicitly when the StreamTokenizer reaches the end of the
stream?
Ans:
Yes, you need to close the Reader stream explicitly when the StreamTokenizer reaches the end of the
stream.