Professional Documents
Culture Documents
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.
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.
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.
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
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.
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;
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
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.
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.
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
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));
}
}
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.
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
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();
}
}
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.
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
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.
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.
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
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.
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
{
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
}
}
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.
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.
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.
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.
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.
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
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.
//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.