Beruflich Dokumente
Kultur Dokumente
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.
In Java, all methods are tied to classes. Java does not support stand-alone methods.
Java does not include the const keyword as present in C or the ability to pass by const
reference explicitly.
In Java strings are implemented as objects and not as an array of null-terminated
characters.
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.
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.
Java does not use pointers.
In Java, arrays are real objects because you can allocate memory using the new operator.
To provide an easy to use language by avoiding pitfalls of other languages and enables
users to create clear and streamlined code.
To provide an interpreted environment for improved speed of development and code
portability.
To provide a way for programs to run more than one thread of activity.
To furnish better security.
Reusability: Elimination of redundant code and use of existing classes through inheritance.
Thus provides economy of expression.
Modularity: Programs can be the built from standard working modules.
Security: Principle of information hiding helps programmer to build secure programs.
Easy mapping: Object in the problem domain can be directly mapped to the objects in the
program.
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.
Easy management: Easy management of software complexity.
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.
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.
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.
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.
One of the striking features of object-oriented programming is the division of programs into
objects that represent real-world entities.
Ans.True
One problem with OOP is that once a class is created, it can never be changed.
Ans. True
Inheritance means the ability to reuse the data values of one object by other objects.
Ans. True
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.
Reserved Keywords
Identifiers
Literals
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:
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:
Integer literals
Floating point literals
Character literals
String literals
Boolean literals
Operators
An operator is a symbol that takes one or more operands and operates on them to produce a result.
They can have alphabets, digits, and the underscore and dollar sign characters.
They must not begin with a digit
Uppercase and lowercase letters are distinct.
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:
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
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;
Instance Variables
Class variables
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.
Ans.
The following are invalid constants:
Ans.
The following are invalid variable names:
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();
}
}
Solutions to Chapter Five Questions
1. Which of the following arithmetic expressions are valid?
a) 25/3 % 2 e) -14 % 3
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.
2m1m 2
b) Torque = *g
m1m 2
c) Side = √a2 + b2 – 2ab cos(x)
velocity2
d) Energy = mass acceleration * height +
2
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
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));
}
}
7. In inventory management, the Economic Order Quality for a single item is given by
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));
}
}
(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))
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:
Purchase Discount
Amount
Mill Cloth Handloom Items
0-100 - 5.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();
}
}
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.
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:
color: red, green, silver, brown.
make: Honda, BMW, Bultaco.
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.
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.
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
}
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).
Arrays of any type can be created. They can have one or more dimensions.
Any specific element can be indexed in an array by its index.
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]
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.
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
{
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
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) 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
}
}
Declare the package at the beginning of a file using the package keyword.
package <package_name>
Define the class that is to be put into the package and declare it public.
Create the subdirectory under the directory where the main source file is stored.
Store the listing as the class_name.java file in the subdirectory.
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");
}
}
}
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.
Byte stream classes that provide support for handling I/O operations on bytes.
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.