Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Corejava 1

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

1

Java Virtual Machine And related top

a)Define Java Virtual Machine?

Ans:

Java Virtual Machine. An abstract computing machine, or virtual machine, JVM


is a platform-independent execution environment that converts Java byte code
into machine language and executes it. Most programming languages compile
source code directly into machine code that is designed to run on a specific
microprocessor architecture or operating system, such as Windows or UNIX. A
JVM -- a machine within a machine -- mimics a real Java processor, enabling
Java bytecode to be executed as actions or operating system calls on any
processor regardless of the operating system. For example, establishing a
socket connection from a workstation to a remote machine involves an
operating system call. Since different operating systems handle sockets in
different ways, the JVM translates the programming code so that the two
machines that may be on different platforms are able to connect

b)Describe the steps to execute a java program?

Ans:

Skarifahmed@gmail.com
2

Programs intended to run on a JVM must be compiled into a standardized


portable binary format, which typically comes in the form of .class files. A
program may consist of many classes in different files. For easier distribution
of large programs, multiple class files may be packaged together in a .jar file
(short for Java archive).

The JVM runtime executes .class or .jar files, emulating the JVM instruction
set by interpreting it, or using a just-in-time compiler (JIT) such as Sun's
HotSpot. JIT compiling, not interpreting, is used in most JVMs today to
achieve greater speed. Ahead-of-time compilers that enable the developer to
precompile class files into native code for a particular platform also exist.

Like most virtual machines, the Java Virtual Machine has a stack-based
architecture.

The JVM, which is the instance of the JRE (Java Runtime Environment), comes
into action when a Java program is executed. When execution is complete,
this instance is garbage-collected. JIT is the part of the JVM that is used to
speed up the execution time. JIT compiles parts of the byte code that have
similar functionality at the same time, and hence reduces the amount of time
needed for compilation.

c) What is Java Virtual Machine specification?

Ans:

The Java Virtual Machine Specification, by Tim Lindholm and Frank Yellin,
outlines what determines a JVM . The specification defines three
components:

Firstly, the JVM must accept bytecode instructions. Bytecodes define the
instruction set that executes the user‘s application program . Each of
the JVM ‘s stack-based instructions consist of a one-byte *opcode
immediately followed by zero or more operands. The JVM ‘s instruction
set defines 200 standard opcodes, 25 quick variations of some opcodes (to
support dynamic binding), and three reserved opcodes. The opcodes dictate
to the JVM what action to perform .

Skarifahmed@gmail.com
3

Secondly, a binary form at known as the class file form at, must be used to
convey bytecodes and related class infrastructure in a platform –
independent manner. Static tools such as class file viewers can look at this
representation.

Finally, a verification algorithm must be used for identifying program s that


will not compromise the integrity of the JVM . A verifier is a key component of
the Java security architecture. It will check that the code respects the syntax
of the bytecode language and that it respects the language rules

*Opcode

A computer can perform operations, each of which is assigned a numeric code


called an opcode. Since humans are terrible at memorizing lots of similar
numeric codes, mnemonics are used as textual abbreviations. It's much easier
to remember ADD than 05, for example.

Opcodes operate on registers, values in memory, values stored on the stack,


i/o ports, the bus, etc. They are used to perform arithmetic operations and
move and change values. Operands are the things that Opcodes operate on

d) Describe about the different components of JVM?

Ans:

ClassLoader:

A class loader is an object that is responsible for loading classes. The class
ClassLoader is an abstract class. Given the name of a class, a class loader
should attempt to locate or generate data that constitutes a definition for the
class. A typical strategy is to transform the name into a file name and then
read a "class file" of that name from a file system.

ByteCode Verfied

ByteCode Is Verfied in two phases:

1.In the first phase,the verifier cheak for the stucture of the .class file.

2. the second level phase occurs when the bytecode is rub.The ByteCode

Verifier checks the validity of the classes,variable,and methods used in a

Skarifahmed@gmail.com
4

program.

security manager :

A security manager is any class that descends from class


java.lang.SecurityManager. Because they are written in Java, security
managers are customizable. A security manager allows you to establish a
custom security policy for an application.

Interpreter

an interpreter each bytecode instruction is read and translated to


machine code.

just-in-time compiler

just-in-time compiler, a code generator that converts Java bytecode into


machine language instructions. Some Java Virtual Machines (VMs), including
the VM in the Netscape Navigator browser, include a JIT in addition to a Java
interpreter. Java programs compiled by a JIT generally run much faster than
when the bytecode is executed by an interpreter.

* difference between interpreter and JIT?

1. In an interpreter each bytecode instruction is read and translated to


machine code.

2. In a compiler JIT, blocks of byte code are compiled at runtime


to machine code.

Overview of Object Oriented Programming

a) What are the basic features of Object Oriented Programming?

Ans:

 Abstraction

 Encapsulation

 Polymorphism

Skarifahmed@gmail.com
5

 Inheritance

b) What are encapsulation,abstraction,inheritance an


polymorphism?Give real world examples of each.

Abstraction denotes the essential charecteristics of an object that


distinguishes it from all other kind of objects and thus provides crisply
conceptual boundaries,relative to perspective of the viewer..

Realworld example:

In a sense, when someone works on a computer, not necessary that he


should know the working of each and every part of the computer. Even
without the hardware knowledge, he can e-mail, type or do other jobs on the
computer. Thus people do not think of a computer as a unit made up of
hundreds of cards and chips, but as a well-defined object with its own unique
behavior. This is the advantage of abstraction.

1)Encapsulation
It is the mechanism that binds together code and data in manipulates, and
keeps both safe from outside interference and misuse. In short it isolates a
particular code and data from all other codes and data. In Java, the basis of
encapsulation is the class. A class defines the structure and behavior(data and
code) that will be shared by a set of objects.

Real world example:

To relate this to the real world, consider the automatic transmission on an


automobile. It encapsulates hundreds of bits of information about your
engine, such as how much you are accelerating, the pitch of the surface you
are on, and the position of the shift lever. You, as the user, have only one
method of affecting this complex encapsulation: by moving the gear-shift
lever. You can't affect the transmission by using the turn signal or windshield
wipers, for example. Thus, the gear-shift lever is a well-defined (indeed,
unique) interface to the transmission. Further, what occurs inside the
transmission does not affect objects outside the transmission. For example,
shifting gears does not turn on the headlights! Because an automatic

Skarifahmed@gmail.com
6

transmission is encapsulated, dozens of car manufacturers can implement one


in any way they please.

2) Inheritance:
It is the process by which one object acquires the properties of another
object. This supports the hierarchical classification. Without the use of
hierarchies, each object would need to define all its characteristics explicitly.

Realworld example:

• Every “Student” is a “Person”


• Every “Lecturer” is a “Person”
• Any “Student” is not a “Lecturer”
• Any “Lecturer” is not a “Student”

From the above, we can decide that “Student” or “Lecturer” belong to the
“Person” category. Thus “Person” will be the super (or parent) class for both
“Student” and “Lecturer.” Conversely, “Student” and “Lecturer” both get
inherited from “Person.”

3) Polymorphism:
Process of aquiring properies from one object to another with
changes.

poly=many , morphism=forms

It is a feature that allows one interface to be used for general class of


actions.In general polymorphism means "one interface, multiple methods",
Thismeans that it is possible to design a generic interface to a group of related
activities.

Realworld example: when a man is in office his role is as an employee,the


same man when is in home his role is as an ordinary housemember.

c) Define class and object.

Ans:

Object and Class

 Object is the basic runtime entities in the object oriented system.

Skarifahmed@gmail.com
7

 Class is the basic structure & behavior of a specific type of objects.

 In the real world, you often have many objects of the same kind. For
example, your bicycle is just one of many bicycles in the world. Using
object-oriented terminology, we say that your bicycle object is an instance
of the class of objects known as bicycles.

 Bicycles have some state (current gear, current cadence, two wheels) and
behavior (change gears, brake) in common.

 Each bicycle's state is independent of and can be different from other


bicycles.

d) What do you mean by state and behavior of an object?

Ans:

Objects are key to understanding object-oriented technology. Look around


right now and you'll find many examples of real-world objects: your dog, your
desk, your television set, your bicycle.

Real-world objects share two characteristics: They all have state and
behavior. Dogs have state (name, color, breed, hungry) and behavior
(barking, fetching, wagging tail). Bicycles also have state (current gear,
current pedal cadence, current speed) and behavior (changing gear, changing
pedal cadence, applying brakes). Identifying the state and behavior for real-
world objects is a great way to begin thinking in terms of object-oriented
programming.

Skarifahmed@gmail.com
8

e) What is the difference between a reference and an object?

Ans:

Reference means address of object or variable.


Object is instance of class .

Object is obtained when it has a life, means it has occupied some memory.
Reference points to the Object.

 When you pass an object variable into a method, you must keep in mind
that you’re passing the object reference, and not the actual object itself.

 You must remember that you aren’t even passing the actual reference
variable, but rather a copy of the reference variable.

 Both the caller and the called method will now have identical copies of the
reference, and thus both will refer to the same exact (not a copy)

Skarifahmed@gmail.com
9

f) What are the differences between class member,instance member


and local member of a class?

Ans:
Variable and method together form a method.

characteristic Local member Instance Class member


member
Where declared In a method, In a class, but In a class, but
constructor of outside a method. outside a method.
block. Must be declared
static.
Use Local variables Each object of the Class has only one
hold values used in class has its own copy of this type of
computations in a copy of this type variable and it is
method. variable. shared by all of the
instances of the
class.
Lifetime Created when Created when Created when the
method or instance of class is program starts.
constructor is created with new. Destroyed when
entered . Destroyed when the program stops.
there are no more
Destroyed on exit references to
from method or enclosing object .
constructor.

Scope/Visibility Local variables are Instance (field) Same as instance


visible only in the variables can been variable, but are
method, seen by all often declared
constructor, or methods in the public to make
block in which they class. constants available
are declared. to users of the
class.

Example Class A Class A Class A


{ { {
void a() int a=0; Static int i=0;
{ void a() }
int a=0; {
} }

Skarifahmed@gmail.com
10

} }

g)Define keyword,Identifier and literal?Give Example.

Keywords:

Keywords are reserved identifiers that are redefined in the language.

All the keywords are in lowercase, and incorrect usage results in compilation
errors. Example –abstract,Boolean etc.

Identifiers:

• Identifiers are the names of variables, methods, classes, packages and


interfaces.

• Identifiers in Java are case sensitive, for example, price and Price are two
different identifiers.

• Example - number, Number, sum_$, bingo, $$_100

• first character in an identifier cannot be a digit

• Each character can be a letter, a digit, a connecting punctuation (such as


underscore _), or any currency symbol (such as $, ¢, ¥, or £).

Literal: By literal we mean any number, text, or other information that


represents a value. This means what you type is what you get. We will use
literals in addition to variables in Java statement. For instance

int month = 10;

In the above statement the literal is an integer value i.e 10. The
literal is 10 because; it directly represents the integer value.

In Java programming language there are some special type of literals that
represent numbers, characters, strings and boolean values.

h) Which of the following is true about identifier and keyword? Why?

Skarifahmed@gmail.com
11

Ans .

i)All keywords are Identifier.

ii)All Identifiers are keywords.

All the keywords are Identifier is true statement.

Because keywords are reserve identifier in java. Identifiers are the names of
variables, methods, classes, packages and interfaces.

Eg. abstract,Boolean is the reserve Identifier.But number, Number, sum_$,


bingo, $$_100 are not the keywords.

i) How many types of primitive datatypes are there in java?

Ans.

Primitive Data Types

Primitive data types in Java can be divided into three main categories:

 Integral types— represent signed integers (byte, short, int, long) and
unsigned character values (char)

 Floating-point types (float, double)— represent fractional signed numbers

 Boolean type (boolean)— represent logical values

Primitive data values are not objects.

Skarifahmed@gmail.com
12

j) Specify the range of values of all integer data types.

Ans:

Data type Minimum value Maximum value


MIN_VALUE MAX_VALUE

byte -2^7 2^7-1

short -2^15 2^15-1

int -2^31 2^31-1

long -2^63 2^63-1

k) Specify the default values of the following data types.

Ans:

i)short ii)byte iii)int iv)long v)boolean vi)float vii)double viii)reference


types

Data Type Default Value (for fields)


byte 0
short 0
int 0
long 0L
float 0.0f
double 0.0d
char '\u0000'

Skarifahmed@gmail.com
13

String (or any object) null


boolean false

l) In java the signature of the main method is public static void


main(String arr[]).Explain the significance of each term

Ans:

public,static,void,main.

 Explanation of public static void main(String args[])

 public:-

The public keyword is an access specifier, which allows the programmer


to control the visibility of class members. When a class member is preceded
by public, then that member may be accessed by code outside the class in
which it is declared.

 static:-

The keyword static allows main( ) to be called without having to


instantiate a particular instance of the class. This is necessary since main( ) is
called by the Java interpreter before any objects are made.

 void - The keyword void simply tells the compiler that main( ) does not
return a value.

 main( ):- main is the method called when a Java application begins. Keep
in mind that Java is case-sensitive. Thus, Main is different from main. It is
important to understand that the Java compiler will compile classes that do
not contain a main( ) method. But the Java interpreter has no way to run
these classes. So, if you had typed Main instead of main, the compiler
would still compile your program. However, the Java interpreter would
report an error because it would be unable to find the main( ) method.

 String arr[]:- Declares a parameter named arr, which is an array of


instances of the class String. (Arrays are collections of similar objects.)
Objects of type String store character strings.

Skarifahmed@gmail.com
14

m)What do you mean by precedence and associativity of the


operators?What is left and right associativity?

Ans:

Precedence are used to determine which operator should be applied first if


there are two or more operators with different precedence in the expression

Operator precedence is why the expression 5 + 3 * 2 is calculated as 5 + (3 *


2), giving 11, and not as (5 + 3) * 2, giving 16.

We say that the multiplication operator (*) has higher "precedence" or


"priority" than the addition operator (+), so the multiplication must be
performed first.

The associativity of an operator is a property that determines how operators


of the same precedence are grouped in the absence of parentheses. Operators
may be left-associative, right-associative or non-associative

Operator associativity is why the expression 8 - 3 - 2 is calculated as (8 - 3) -


2, giving 3, and and not as 8 - (3 - 2), giving 7.

We say that the subtraction operator (-) is "left associative", so the left
subtraction must be performed first. When we can't decide by operator
precedence alone in which order to calculate an expression, we must use
associativity.

n)What is the evaluation order of the operands?Is there any


exceptional case which does not satisfy the normal evaluation order
of the operands?

Ans:
In order to understand the result returned by an operator, it is important to
understand the evaluation order of its operands. Java states that the
operands of operators are evaluated from left to right.Java guarantees that all
operands of an operator are fully evaluated before the operator is applied.
The only exceptions are the short-circuit conditional operators &&, ||,
and ?:.

Skarifahmed@gmail.com
15

In the case of a binary operator, if the left-hand operand causes an exception ,


the right-hand operand is not evaluated. The evaluation of the left-hand
operand can have side effects that can influence the value of the right-hand
operand. For example, in the following code:
int b = 10;
System.out.println((b=3) + b);
the value printed will be 6 and not 13. The evaluation proceeds as follows:

(b=3) + b
3 + b b is assigned the value 3
3+3
6
The evaluation order also respects any parentheses, and the precedence and
associativity rules of operators.

Skarifahmed@gmail.com
16

o. What is narrowing conversion and widening conversion for


primitive data types and reference types. Give example.

Ans:

Change of one type to another type is called conversion.

Two types of conversion:

1>Narrowing Conversion

a>Narrowing Primitive Conversions

The value of broader data type can be converted to a value of a narrower data
type which can result in loss of information.

Eg. long to int , long to byte

public class MainClass {

public static void main(String[] args) {

long a = 10;

int b = (int) a; // narrowing conversion

System.out.println(a);

System.out.println(b);

b>Narrowing Reference Conversions

Conversions down the inheritance hierarchy are called narrowing reference


conversions

Eg.

Skarifahmed@gmail.com
17

class A{

class B extends A{

public static void main(String arghs[]){

A a=new B();

B b =(B)a; //narrowing reference conversion

2> Widening Conversion

a>Widening Primitive Conversions:

The value of narrower data type can be converted to a value of a brooder data
type without loss of information.

Eg. byte to short, int to long

public class MainClass {

public static void main(String[] args) {

int big = 1234567890;

float approx = big;

b>Widening Reference Conversions

Skarifahmed@gmail.com
18

Conversions up the inheritance hierarchy are called widening reference


conversions

Eg.

class A{

class B extends A{

public static void main(String arghs[]){

A a =new B();//widening reference conversion

p)What is casting? What is upcasting and downcasting? Give example.

Ans :

Casting: casting is the process of converting one data type into another data
type or one reference type into another reference type.

Casting are of two types:

1>Upcasting (Implicit Casting)

a> For primitive type:

It is a process of converting narrower data type to broader data type without


loss of information.

Eg.

class Test {

public static void main(String[] args) {

Skarifahmed@gmail.com
19

int big = 1234567890;

float approx = big;

b> For reference type:

UpCasting for reference type is, casting up the inheritance tree to a more
general type. It is done implicitly (i.e. typing in the cast is not required). Its
because the classes at lower level of hierarchy have all those features that are
present in the classes above them in the inheritance hierarchy. So they can be
up casted implicitly.

Eg.

class A{

class B extends A{

public static void main(String arghs[]){

A a =new B();//upcasting

2>Down casting:

a>For primitive type:

It is a process of converting broader data type to narrower data type with loss
of information.

Skarifahmed@gmail.com
20

public class MainClass {

public static void main(String[] args) {

long a = 10;

int b = (int) a; // narrowing conversion

System.out.println(a);

System.out.println(b);

b>For reference type:

Down Casting for reference type is nothing but casting down the inheritance
tree to a more specific class i.e casting a superclass to subclass.

Eg.

class A{

class B extends A{

public static void main(String arghs[]){

A a=new B();

B b =(B)a;//downcasting

Skarifahmed@gmail.com
21

q)What is numeric promotion?What are unary numeric promotion and


binary numeric promotion?

Ans.

Numeric promotion :

• Numeric promotion is applied to the operands of an arithmetic operator.

• Numeric promotions are used to convert the operands of a numeric


operator to a common type so that an operation can be performed.

• The two kinds of numeric promotion are unary numeric promotion and
binary numeric promotion.

 Unary Numeric Promotion

Some operators apply unary numeric promotion to a single operand, which


must produce a value of a numeric type:

• If the operand is of compile-time type byte, short, char, or int it is


subjected to conversion. The result is then promoted to a value of type int
by a widening conversion or an identity conversion.

• Otherwise, a unary numeric operand remains as is and is not converted.

 Binary Numeric Promotion

Binary numeric promotion implicitly applies appropriate widening primitive


conversions so that a pair of operands have the broadest
numeric type of the two, which is always at least int. Given T to be the
broadest numeric type of the two operands, the operands are
promoted as follows under binary numeric promotion.
If T is broader than int, both operands are converted to T; otherwise, both
operands are converted to int.
This means that byte, short, and char are always converted to int at least.

r) What are the differences between bitwise &,| operator

and &&,|| operator?

Skarifahmed@gmail.com
22

Ans.
Logical AND (&), x & y true if both operands are true; otherwise, false.
Logical OR(|) x | y true if either or both operands are true; otherwise,f alse.

Conditional operators && and || are similar to their counterpart logical


operators & and |, except that their evaluation is *short-circuited.
Given that x and y represent values of boolean expressions,. In the table, the
operators are listed in decreasing precedence order.
Conditional Operators
Conditional AND x && y true if both operands are true; otherwise, false.
Conditional OR x || y true if either or both operands are true; otherwise, false.
Unlike their logical counterparts & and |, which can also be applied to integral
operands for bitwise operations, the conditional operators
&& and || can only be applied to boolean operands. Their evaluation results in
ab oolean value. Not surprisingly, they have the same truth-values as their
counterpart logical operators. Note that, unlike their logical counterparts,
there are no compound assignment operators for the conditional operators.

*Short circuit operator:- <expression1>short circuit operator(&&,||)


<expression2>

1.evaluates its second operand(expression2)only if the first


operand(expression1)returns true

2.Not to evaluate its second operand(expression2)only if the first


operand(expression1)returns false..

Skarifahmed@gmail.com
23

s)What is message passing in java?How many types of message


passing are there in java?Give examples of each.

Ans:

Message passing:

 Objects communicate by sending messages.


 Messages convey some form of information.
 An object requests another object to carry out an activity by sending it a
message.
 Most messages pass arguments back and forth.
Message passing:

 Passing Object Reference Variables


 Passing Primitive Variables

Passing Object Reference Variables

When you pass an object variable into a method, you must keep in mind that
you’re passing the object reference, and not the actual object itself.

 You must remember that you aren’t even passing the actual reference
variable, but rather a copy of the reference variable.
 Both the caller and the called method will now have identical copies of the
reference, and thus both will refer to the same exact (not a copy) object on
the heap.

Passing Object Reference Variables Example:

import java.awt.Dimension;

class ReferenceTest {

public static void main (String [] args) {

Dimension d = new Dimension(5,10);

ReferenceTest rt = new ReferenceTest();

System.out.println("Before modify() d.height = " + d.height);

Skarifahmed@gmail.com
24

rt.modify(d);

System.out.println("After modify() d.height = " + d.height);

void modify(Dimension dim) {

dim.height = dim.height + 1;

System.out.println("dim = " + dim.height);

Output Of The Previous Example:

Before modify() d.height = 10

dim = 11

After modify() d.height = 11

Passing Primitive Variables:

class ReferenceTest {

public static void main (String [] args) {

int a = 1;

ReferenceTest rt = new ReferenceTest();

System.out.println("Before modify() a = " + a);

rt.modify(a);

System.out.println("After modify() a = " + a);

void modify(int number) {

Skarifahmed@gmail.com
25

number = number + 1;

System.out.println(“ number = " + number);

Passing Primitive Variables:

 The variable a is passed to a method called modify(), which increments the


variable by 1. Output –
 Before modify() a = 1
number = 2

After modify() a = 1

a did not change after it was passed to the method. Remember, it was only a
copy of a that was passed to the method. When a primitive variable is passed
to a method, it is pass by value, which means pass-by-copy-of-the-bits-in
the variable

t)What are the significance of following access modifier?

i)static ii)final iii)abstract iv)transient v)native

Ans:

 static - Static members belong to the class in which they are declared, and
are not part of any instance of the class.

Depending on the accessibility modifiers of the static members in a class,


clients can access these by using the class name, or through object references
of the class.

When the class is loaded, static variables are initialized to their default values.

A static method in a class can directly access other static members in the
class. It cannot access instance (i.e., non-static) members of the class.

 final - The final modifier applies to classes, methods, and variables.

A final class cannot be inherited.

Skarifahmed@gmail.com
26

A final variable of a primitive data type cannot change its value once it has
been initialized.

A final method in a class is complete (i.e., has an implementation) and cannot


be overridden in any subclass.

 abstract - An abstract class is a class that is declared abstract—it may or


may not include abstract methods. Abstract classes cannot be instantiated,
but they can be subclassed.

An abstract method is a method that is declared without an implementation


(without braces, and followed by a semicolon), like this:
abstract void moveTo(double deltaX, double deltaY);

If a class includes abstract methods, the class itself must be declared


abstract, as in:

public abstract class GraphicObject {


// declare fields
// declare non-abstract methods
abstract void draw();
}

When an abstract class is subclassed, the subclass usually provides


implementations for all of the abstract methods in its parent class. However, if
it does not, the subclass must also be declared abstract.

 native Method- Their implementation is not defined in Java but in another


programming language

class Native { /* * The static block ensures that the native method library * is
loaded before the native method is called. */ static {
System.loadLibrary(“ NativeMethodLib"); // (1) Load native library.

native void nativeMethod(); // (2) Native method prototype. // ...

Skarifahmed@gmail.com
27

 transient- Objects can be stored using serialization.Serialization


transforms objects into an output format that is conducive for storing
objects. Objects can later be retrieved in the same state as when they
were serialized, meaning that all fields included in the serialization will
have the same values as at the time of serialization. Such objects are said
to be persistent.Transient variable can't be serialize.
For example if a variable is declared as transient in a Serializable class
and the class is written to an ObjectStream, the value of the variable can't be
written to the stream instead when the class is retrieved from the
ObjectStream the value of the variable becomes null.
transient int currentTemperature; // (1) Transient value

u) What are the significance of following access specifier?

i) public ii)private iii)protected iv)default

Ans:

Public:

public classes, methods, and fields can be accessed from everywhere. The
only constraint is that a file with Java source code can only contain one public

Skarifahmed@gmail.com
28

class whose name must also match with the filename. If it exists, this public
class represents the application or the applet, in which case the public
keyword is necessary to enable your Web browser or appletviewer to show the
applet. You use public classes, methods, or fields only if you explicitly want to
offer access to these entities and if this access cannot do any harm. An
example of a square determined by the position of its upper-left corner and its
size:
public class Square { // public class
public x, y, size; // public instance variables
}

Protected:

protected methods and fields can only be accessed within the same class to
which the methods and fields belong, within its subclasses, and within classes
of the same package, but not from anywhere else. You use the protected
access level when it is appropriate for a class's subclasses to have access to
the method or field, but not for unrelated classes.

default (no specifier):

If you do not set access to specific level, then such a class, method, or field
will be accessible from inside the same package to which the class, method, or
field belongs, but not from outside this package. This access-level is
convenient if you are creating packages. For example, a geometry package
that contains Square and Tiling classes, may be easier and cleaner to
implement if the coordinates of the upper-left corner of a Square are directly
available to the Tiling class but not outside the geometry package.

Private:

private methods and fields can only be accessed within the same class to
which the methods and fields belong. private methods and fields are not
visible within subclasses and are not inherited by subclasses. So, the private
access specifier is opposite to the public access specifier. It is mostly used for
encapsulation: data are hidden within the class and accessor methods are
provided. An example, in which the position of the upper-left corner of a
square can be set or obtained by accessor methods, but individual coordinates
are not accessible to the user.
public class Square { // public class
private double x, y // private (encapsulated) instance variables

Skarifahmed@gmail.com
29

public setCorner(int x, int y) { // setting values of private fields


this.x = x;
this.y = y;
}

public getCorner() { // setting values of private fields


return Point(x, y);
}
}

v)Define array? What is anonymous array? Give an example of two


dimensional array. Give a real world scenario which can be
implemented by using multidimensional array.

Ans:

Array:

 An array is a data structure that defines an indexed collection of a fixed


number of homogeneous data elements. In java, all arrays are indexed by
integers, starting from zero.
 An array is an object, and an array variable is a reference
 For Example , we can visualize an array called a of 10 integers as follows:

Example of Array-
class Gauss {
public static void main(String[] args) {
int[] ia = new int[101];
for (int i = 0; i < ia.length; i++)
ia[i] = i;
int sum = 0;
for (int i = 0; i < ia.length; i++)
sum += ia[i];
System.out.println(sum);
}

Skarifahmed@gmail.com
30

}
that produces the output:
5050

Anonymous Arrays:

No array name or array size is specified for the anonymous array i.e. both
combine the definition and initialization of array into one process.

class AnonArray {

public static void main(String[] args) {

System.out.println("Minimum value: " + findMinimum(new int[] {3, 5, 2, 8,


6}));

public static int findMinimum(int[] dataSeq) {

int min = dataSeq[0];

for (int index = 1; index < dataSeq.length; ++index)

if (dataSeq[index] < min)

min = dataSeq[index];

return min;

Output from the program:

Minimum value: 2

Two or Multi dimensional array:

int[][] table = new int[10][20];

Skarifahmed@gmail.com
31

for(int row=0; row<10;row++)

for(int col=0; col<20; col++)

table[row][col] = 0; //set all array elements to 0

 Or, using the length instance variables


for(int row=0; row<table.length; row++)

for(int col=0; col<table[row].length; col++)

table[row][col] = 0; //set all array elements to 0

Real world scenario:

When constructing multidimensional arrays with the new operator, the length
of the deeply nested arrays may be omitted. In this case,
these arrays are left unconstructed. For example an array of arrays to
represent a room on a floor in a hotel on a street in a city can have
the type HotelRoom[][][][]. From left to right, the square brackets represent
indices for street, hotel, floor, and room, respectively. This
4-dimensional array of arrays can be constructed piecemeal, starting with the
leftmost dimension and proceeding to the rightmost.
HotelRoom[][][][] rooms = new HotelRoom[10][5][][]; // Just streets and
hotels.
The above declaration constructs the array of arrays rooms partially with ten
streets, where each street has five hotels. Floors and rooms
can be added to a particular hotel on a particular street:
rooms[0][0] = new HotelRoom[3][]; // 3 floors in 1st. hotel on 1st. street.
rooms[0][0][0] = new HotelRoom[8]; // 8 rooms on 1st. floor in this hotel.
rooms[0][0][0][0] = new HotelRoom(); // Initialize 1st. room on this floor.

w) What do you mean by Compile time Polymorphism and Run time


Polymorphism and Why? Write a piece of code which implement these
two concepts.

Ans:

Compile-time polymorphism :

Skarifahmed@gmail.com
32

For each method invocation, the compiler determines which method (from a
group of overloaded methods) will be executed, and this decision is made
when the program is compiled.

Run-time polymorphism:

The decision as to which version of the method to execute is based on the


actual type of object whose reference is stored in the reference variable, not
on the type of the reference variable on which the method is invoked.

The reason that this type of polymorphism is often referred to as runtime


polymorphism is because the decision as to which version of the method to
execute cannot be made until runtime. The decision cannot be made at
compile time.

class A
{
void method(int x)\\1
{
}
int method(String s)\\2
{
}
}
class B extends A{
void method(int a)\\3
{
}
public static void main(String a[]){
A a=new B();\\4
a.method(5);\\5
a.method(“name”);\\6
}
}
Explanation:

At compile time the methods marked 1 and will be checked whether method
overloading is occurring.

Skarifahmed@gmail.com
33

In case of line 4 ‘a’ store the reference of ‘class A’,

when ‘a.method(5)’ will execute it is checked with void ‘method(int)’ whether


it is being overridden and this is checked at run time.

x)What is constructor? What the differences are between


parameterized and default constructor. Give example.

Ans:

Constructor

 The main purpose of constructors is to set the initial state of an object


when the object is created by using the new operator.
 Constructors cannot be inherited or overridden.
 They can be overloaded, but only in the same class.
 Since a constructor always has the same name as the class, each
parameter list must be different when defining more than one constructor
for a class.
Default Constructor

 A default constructor is a constructor without any parameters. In other


words, it has the following signature:
<class name>()

 If a class does not specify any constructors, then an implicit default


constructor is supplied for the class. The implicit default constructor is
equivalent to the following implementation:
<class name>() { super(); } // No parameters. Calls superclass
constructor.

Parameterized Constructor

 Constructors can also be overloaded. Since the constructors in a class all


have the same name as the class, their signatures are differentiated by
their parameter lists.
 Example:
class Light {

// .....

Skarifahmed@gmail.com
34

// Parameterized Constructor

Light(int noOfWatts, boolean indicator, String location)

{ this.noOfWatts = noOfWatts;

this.indicator = indicator;

this.location = location;

// ……

y) Define package. Which of the features of Object Oriented Concept


is implemented by package.

Ans:

Packages are containers for classes that are used to keep the class name
space compartmentalized.
For example, a package allows you to create a class named List, which you
can store in your own package without concern that it will collide with some
other class named List stored elsewhere. To create a package is quite easy:
simply include a package command as the first statement in a Java source
file.

This is the general form of the package statement:


package pkg;

 The main features of OOP implemented by package.:

 Inheritence (Extending the classes)

 Encapsulation

Skarifahmed@gmail.com
35

z)What are the differences between abstract class and interface?Give


example.

Ans:

Interfaces vs Abstract Classes

Interface Abstract class

A class may implement several A class may extend only one abstract
interfaces. class.

An interface cannot provide any code An abstract class can provide complete
at all, much less default code. code, default code.

Slow, requires extra indirection to Fast


find the corresponding method in the
Abstract class – Example
actual class. Modern JVMs are
discovering ways to reduce this abstract class Shape {
speed penalty.Declaring an
Interface: public String color;

Access specifier interface name { public Shape( ) { }

return-type method- public void setColor( String c ){


name1(parameter-list);
color = c;
return-type method-
}
name2(parameter-list);
public String getColor( ) {
type final-varname1 = value;

Skarifahmed@gmail.com
36

type final-varname2 = value; return color;

// ... }

return-type method- abstract public double area( );


nameN(parameter-list);
}
type final-varnameN = value;

Interfaces vs. Abstract Classes

 An Interface can only have public members whereas an abstract class can
contain private,public,default as well as protected members.
 All variables in an Interface are by default - public static final while an
abstract class can have instance variables.
 Abstract class definition begins with the keyword "abstract" keyword
followed by Class definition. An Interface definition begins with the
keyword "interface".

Exception Handling & Flow Control

a) What is the difference between break and continue statement?

Ans:

The continue Statement:

 The continue statement skips the current iteration of a for, while , or do-
while loop.

Skarifahmed@gmail.com
37

 the continue statement transfers control when it is executed; that is, the
rest of the loop body is skipped and execution continues with the next
iteration of the inner loop

The continue Statement example:

for (int i = 0; i < max; i++)

if (searchMe.charAt(i) != 'p')

continue;

numPs++;

The break Statement:

 The break statement has two forms: labeled and unlabeled.

 Break can be used to terminate a for, while, or do-while loop

The break Statement example:

For(int i=0;i<=10;i++)

if(i==6)break;

System.out.println(“Example of break”);

b)What is the difference between while and do-While loop?

Ans:

The difference between a "do ...while" loop and a "while {} " loop is that the
while loop tests its condition before execution of the contents of the loop
begins; the "do " block tests its condition after it's been executed at least

Skarifahmed@gmail.com
38

once. If the test condition is false as the while block is entered the block of
code is never executed. Since the condition is tested at the bottom of a do-
while loop, its block of code is always executed at least once.

While:Entry Controlled loop


The while loop is used to execute a block of code as long as some condition is
true. If the condition is false , the block of code is not executed at all. The
while loop tests the condition before it's executed so sometimes the loop may
never be executed if initially the condition is not met. Its syntax is as follows.

while (tested condition is satisfied)


{
block of code
}

No semi-colons ( ; ) are to be used after the while (condition) statement.


These loops are very useful because the condition is tested before execution
begins.

do ....while:Exit Controlled loop


The do loop also executes a block of code as long as a condition is satisfied.

The "do ....while" loops syntax is as follows

do
{
block of code
} while (condition is satisfied);

A semi-colon ( ; ) must be used at the end of the do ...while loop. This semi-
colon is needed because it instructs whether the while (condition) statement is
the beginning of a while loop or the end of a do ...while loop.

c) What is meant by stack-based execution and exception


propagation?

Ans:

Stack based execution:

 Several threads can be executing in the JVM.

Skarifahmed@gmail.com
39

 Each thread has its own runtime stack (also called the call stack or the
invocation stack) that is used to handle execution of methods.

 Each element on the stack corresponds to a method call

 When the method finishes executing, its record is popped from the stack.

 At any given time, the active methods on a runtime stack comprise what is
called the stack trace of a thread's execution.

Exception propagation:

It means how an exception propagates within a program from one method to


another while the program runs.

Example:

public class Average1 {


public static void main(String[] args) {
printAverage(100,0);
2. System.out.println("Exit main().");
}
public static void printAverage(int totalSum, int totalNumber) {
int average = computeAverage(totalSum, totalNumber);
4. System.out.println("Average = " +
totalSum + " / " + totalNumber + " = " + average);
5. System.out.println("Exit printAverage().");}
public static int computeAverage(int sum, int number) {
System.out.println("Computing average.");
return sum/number;
}
}
Output of program execution:
Computing average.
Exception in thread "main" java.lang.ArithmeticException: / by zero
at Average1.computeAverage(Average1.java:18)
at Average1.printAverage(Average1.java:10)
at Average1.main(Average1.java:5)

Explanation of the example:

Skarifahmed@gmail.com
40

All goes well until the return statement in the method computeAverage() is
executed. An error condition occurs in calculating the expression sum/number,
because integer division by 0 is an illegal operation. This error condition is
signalled by the JVM by throwing an ArithmeticException. This exception is
propagated by the JVMthrough the runtime stack . Execution of the
computeAverage() method is stopped at the point where the exception is
thrown. The execution of the return statement never gets completed. Since
this method does not have any code to deal with the exception, its execution
is likewise terminated abruptly and its activation record popped. We say that
the method completes abruptly. The exception is then offered to the method
whose activation is now on top of the stack (method printAverage()). This
method does not have any code to deal with the exception either, so its
execution completes abruptly. Lines (4) and (5) in the method rintAverage()
never get executed. The exception now propagates to the last active method
(method main()). This does not deal with the exception either. The main()
method also completes abruptly. Line (2) in the main() method never gets
executed. Since the exception is not caught by any of the active methods, it is
dealt with by the main thread's default exception handler. The default
exception handler usually prints the name of the exception, with an
explanatory message, followed by a printout of the stack trace at the time the
exception was thrown. An uncaught exception results in the death of the
thread in which the exception occurred.

d)What are the utilities of try,catch and finally block?

Ans:

Exception Handling: try, catch, and finally

The mechanism for handling exceptions is embedded in the try-catch-finally


construct, which has the following general form:

try { // try block

<statements>

} catch (<exception type1> <parameter1>) { // catch block

<statements>

Skarifahmed@gmail.com
41

...

catch (<exception typen> <parametern>) { // catch block

<statements>

} finally { // finally block

<statements>

Exceptions thrown during execution of the try block can be caught and
handled in a catch block. A finally block is guaranteed to be executed,
regardless of the cause of exit from the try block, or whether any catch block
was executed.

try Block

The try block establishes a context that wants its termination to be handled.
Termination occurs as a result of encountering an exception ,or from
successful execution of the code in the try block.

For all exits from the try block, except those due to exceptions, the catch
blocks are skipped and control is transferred to the finally block, if one is
specified

For all exits from the try block resulting from exceptions, control is transferred
to the catch blocks—if any such blocks are specified—to find a matching catch
block .If no catch block matches the thrown exception, control is transferred
to the finally block, if one is specified

catch Block

Only an exit from a try block resulting from an exception can transfer control
to a catch block. A catch block can only catch the thrown exception if the
exception is assignable to the parameter in the catch block .The code of the
first such catch block is executed and all other catch blocks are ignored. On
exit from a catch block, normal execution continues unless there is any
pending exception that has been thrown and not handled. If this is the case,

Skarifahmed@gmail.com
42

the method is aborted and the exception is propagated up the runtime stack
as explained earlier. After a catch block has been executed, control is always
transferred to the finally block, if one is specified. This is always true as long
as there is a finally block, regardless of whether the catch block itself throws
an exception.

finally Block

 A finally block encloses code that is always executed at some point after
the try block, whether an exception was thrown or not.

 If there is a return statement in the try block, the finally block executes
right after the return statement!

 This is the right place

 to close your files,

 release your network sockets,

 perform any other cleanup your code requires.

e) What is the difference between checked Exception and unchecked


Exception? Give example.

Ans:

Checked exceptions: -

 Except for RuntimeException, Error, and their subclasses, all exceptions are
called checked exceptions.

The compiler ensures that if a method can throw a checked exception, directly
or indirectly, then the method must explicitly deal with it. The method must
either catch the exception and take the appropriate action, or pass the
exception on to its caller

Example: IOException

Unchecked Exceptions:-

Skarifahmed@gmail.com
43

 Exceptions defined by Error and RuntimeException classes and their


subclasses are known as unchecked exceptions.

 They are either irrecoverable and the program should not attempt to deal
with them.

 Exceptions defined by Error and RuntimeException classes and their


subclasses are known as unchecked exceptions, meaning that a method is
not obliged to deal with these kinds of exceptions .They are either
irrecoverable and the program should not attempt to deal with them, or
they are programming errors
and should be dealt with as such and not as exceptions.

Example:NullPointerException

f)What is the difference between exception and error?

Ans :

Exception and Error are the subclasses of the Throwable class. Exception class
is used for exceptional conditions that user program should catch. With
exception class we can subclass to create our own custom exception.

The subclasses of Error represent errors that are normally thrown by the class
loader, the virtual machine, or other support code. Application-specific code
should not normally throw any of these standard error classes. If a method
does throw an Error class or any of its subclasses, the method is not required
to declare that fact in its throws clause. Error defines exceptions that are not
expected to be caught by you program. Example is Stack Overflow.

g)What is the difference between throw and throws clause?

Ans:

A program can explicitly throw an exception using the throw statement. The
general format of the throw statement is as follows:

throw <object reference expression>

Skarifahmed@gmail.com
44

That means whenever we want to force an exception then we use throw


keyword. the throw keyword is used to force an exception. throw keyword
can also be used to pass a custom message to the exception handling module
i.e. the message which we want to be printed. For instance in the above
example we have used –

Example of throw clause:-

package test;

class MyException extends Exception {

public MyException(String msg) {

super(msg);

public class Test {

static int divide(int first, int second) throws MyException {

if (second == 0) {

throw new MyException("can't be divided by zero");

return first / second;

public static void main(String[] args) {

try {

System.out.println(divide(4, 0));

} catch (MyException exc) {

Skarifahmed@gmail.com
45

exc.printStackTrace();

A throws clause can be specified in the method protoype.


... someMethod(...)
throws <ExceptionType1>, <ExceptionType2>,..., <ExceptionTypen> { ... }

The compiler enforces that the checked exceptions thrown by a method are
limited to those specified in its throws clause. Of course, the method can
throw exceptions that are subclasses of the checked exceptions in the throws
clause.

Any method that can cause a checked exception to be thrown, either


directly by using the throw statement or indirectly by invoking other methods
that can throw such an exception, must deal with the exception in one of
three ways. That are

• use a try block and catch the exception in a handler and deal with it.
• use a try block and catch the exception in a handler, but throw another
exception that is either unchecked or declared in its throws clause
• explicitly allow propagation of the exception to its caller by declaring it in
the throws clause of its method prototype.

Example:-

Definition of printAverage()

void printAverage(int num1,int num2)

throws Exception {

//some line of code

Skarifahmed@gmail.com
46

Now inside main :

try {

printAverage(100, 0); //when we call this metod

//compiler force to put the code into try catch


//block because this method throws Exception

} catch (Exception e) {

e.printStackTrace();

System.out.println("Exception handled in " +

"main().");

} finally {

System.out.println("Finally done in main().");

Skarifahmed@gmail.com
47

h)Explain Exception Hierarchy.

Ans:

Skarifahmed@gmail.com
48

Exceptions

All of the subclasses of Exception represent exceptional conditions that a


normal Java program may want to handle. Many of the standard exceptions
are also subclasses of RuntimeException. Runtime exceptions represent
runtime conditions that can generally occur in any Java method, so a method
is not required to declare that it throws any of the runtime exceptions.
However, if a method can throw any of the other standard exceptions, it must
declare them in its throws clause.

A Java program should try to handle all of the standard exception classes,
since they represent routine abnormal conditions that should be anticipated
and caught to prevent program termination.

Runtime exceptions

The java.lang package defines the following standard runtime exception


classes:

ArithmeticException

This exception is thrown to indicate an exceptional arithmetic condition, such


as integer division by zero.

ArrayIndexOutOfBoundsException

This exception is thrown when an out-of-range index is detected by an array


object. An out-of-range index occurs when the index is less than zero or
greater than or equal to the size of the array.

ArrayStoreException

This exception is thrown when there is an attempt to store a value in an array


element that is incompatible with the type of the array.

ClassCastException

This exception is thrown when there is an attempt to cast a reference to an


object to an inappropriate type.

Skarifahmed@gmail.com
49

IllegalArgumentException

This exception is thrown to indicate that an illegal argument has been passed
to a method.

IllegalMonitorStateException

This exception is thrown when an object's wait(), notify(), or notifyAll()


method is called from a thread that does not own the object's monitor.

IllegalStateException

This exception is thrown to indicate that a method has been invoked when the
run-time environment is in an inappropriate state for the requested operation.
This exception is new in Java 1.1.

IllegalThreadStateException

This exception is thrown to indicate an attempt to perform an operation on a


thread that is not legal for the thread's current state, such as attempting to
resume a dead thread.

IndexOutOfBoundsException

The appropriate subclass of this exception (i.e.,


ArrayIndexOutOfBoundsException or StringIndexOutOfBoundsException) is
thrown when an array or string index is out of bounds.

NegativeArraySizeException

This exception is thrown in response to an attempt to create an array with a


negative size.

NullPointerException

This exception is thrown when there is an attempt to access an object through


a null object reference. This can occur when there is an attempt to access an
instance variable or call a method through a null object or when there is an
attempt to subscript an array with a null object.

NumberFormatException

Skarifahmed@gmail.com
50

This exception is thrown to indicate that an attempt to parse numeric


information in a string has failed.

RuntimeException

The appropriate subclass of this exception is thrown in response to a runtime


error detected at the virtual machine level. Because these exceptions are so
common, methods that can throw objects that are instances of
RuntimeException or one of its subclasses are not required to declare that fact
in their throws clauses.

SecurityException

This exception is thrown in response to an attempt to perform an operation


that violates the security policy implemented by the installed SecurityManager
object.

StringIndexOutOfBoundsException

This exception is thrown when a String or StringBuffer object detects an out-


of-range index. An out-of-range index occurs when the index is less than zero
or greater than or equal to the length of the string.

Other exceptions

The java.lang package defines the following standard exception classes that
are not runtime exceptions:

ClassNotFoundException

This exception is thrown to indicate that a class that is to be loaded cannot be


found.

CloneNotSupportedException

This exception is thrown when the clone() method has been called for an
object that does not implement the Cloneable interface and thus cannot be
cloned.

Exception

Skarifahmed@gmail.com
51

The appropriate subclass of this exception is thrown in response to an error


detected at the virtual machine level. If a program defines its own exception
classes, they should be subclasses of the Exception class.

IllegalAccessException

This exception is thrown when a program tries to dynamically load a class


(i.e., uses the forName() method of the Class class, or the findSystemClass()
or the loadClass() method of the ClassLoader class) and the currently
executing method does not have access to the specified class because it is in
another package and not public. This exception is also thrown when a
program tries to create an instance of a class (i.e., uses the newInstance()
method of the Class class) that does not have a zero-argument constructor
accessible to the caller.

InstantiationException

This exception is thrown in response to an attempt to instantiate an abstract


class or an interface using the newInstance() method of the Class class.

InterruptedException

This exception is thrown to signal that a thread that is sleeping, waiting, or


otherwise paused has been interrupted by another thread.

NoSuchFieldException

This exception is thrown when a specified variable cannot be found. This


exception is new in Java 1.1.

NoSuchMethodException

This exception is thrown when a specified method cannot be found.

Errors

The subclasses of Error represent errors that are normally thrown by the class
loader, the virtual machine, or other support code. Application-specific code
should not normally throw any of these standard error classes. If a method
does throw an Error class or any of its subclasses, the method is not required
to declare that fact in its throws clause.

Skarifahmed@gmail.com
52

A Java program should not try to handle the standard error classes. Most of
these error classes represent non-recoverable errors and as such, they cause
the Java runtime system to print an error message and terminate program
execution.

The java.lang package defines the following standard error classes:

AbstractMethodError

This error is thrown in response to an attempt to invoke an abstract method.

ClassCircularityError

This error is thrown when a circular reference among classes is detected


during class initialization.

ClassFormatError

This error is thrown when an error is detected in the format of a file that
contains a class definition.

Error

The appropriate subclass of this error is thrown when an unpredictable error,


such as running out of memory, occurs. Because of the unpredictable nature
of these errors, methods that can throw objects that are instances of Error or
one of its subclasses are not required to declare that fact in their throws
clauses.

ExceptionInInitializerError

This error is thrown when an unexpected exception is thrown in a static


initializer. This error is new in Java 1.1.

IllegalAccessError

This error is thrown when a class attempts to access a field or call a method it
does not have access to. Usually this error is caught by the compiler; this
error can occur at run-time if the definition of a class changes after the class
that references it was last compiled.

Skarifahmed@gmail.com
53

IncompatibleClassChangeError

This error or one of its subclasses is thrown when a class refers to another
class in an incompatible way. This situation occurs when the current definition
of the referenced class is incompatible with the definition of the class that was
found when the referring class was compiled. For example, say class A refers
to a method in class B. Then, after class A is compiled, the method is removed
from class B. When class A is loaded, the run-time system discovers that the
method in class B no longer exists and throws an error.

InstantiationError

This error is thrown in response to an attempt to instantiate an abstract class


or an interface. Usually this error is caught by the compiler; this error can
occur at run-time if the definition of a class is changed after the class that
references it was last compiled.

InternalError

This error is thrown to signal an internal error within the virtual machine.

LinkageError

The appropriate subclass of this error is thrown when there is a problem


resolving a reference to a class. Reasons for this may include a difficulty in
finding the definition of the class or an incompatibility between the current
definition and the expected definition of the class.

NoClassDefFoundError

This error is thrown when the definition of a class cannot be found.

NoSuchFieldError

This error is thrown in response to an attempt to reference an instance or


class variable that is not defined in the current definition of a class. Usually
this error is caught by the compiler; this error can occur at run-time if the
definition of a class is changed after the class that references it was last
compiled.

NoSuchMethodError

Skarifahmed@gmail.com
54

This error is thrown in response to an attempt to reference a method that is


not defined in the current definition of a class. Usually this error is caught by
the compiler; this error can occur at run-time if the definition of a class is
changed after the class that references it was last compiled.

OutOfMemoryError

This error is thrown when an attempt to allocate memory fails.

StackOverflowError

This error is thrown when a stack overflow error occurs within the virtual
machine.

ThreadDeath

This error is thrown by the stop() method of a Thread object to kill the thread.
Catching ThreadDeath objects is not recommended. If it is necessary to catch
a ThreadDeath object, it is important to re-throw the object so that it is
possible to cleanly stop the catching thread.

UnknownError

This error is thrown when an error of unknown origins is detected in the run-
time system.

UnsatisfiedLinkError

This error is thrown when the implementation of a native method cannot be


found.

VerifyError

This error is thrown when the byte-code verifier detects that a class file,
though well-formed, contains some sort of internal inconsistency or security
problem.

VirtualMachineError

The appropriate subclass of this error is thrown to indicate that the Java
virtual machine has encountered an error.

Skarifahmed@gmail.com
55

Object oriented programming: Most Advanced Topics

a) Can a static method and a field member be overridden? Explain


with example.

Ans :

No. Static method can’t be overridden.

If a subclass defines a static method with the same signature as a static


method in the superclass, the method in the subclass hides the one in the
superclass.

For example……..

class A {

static int i=5; //1 static variable

public static void staticMethod() {//2 static method

System.out.println("staticMethod () in A");

class B extends A {

static int i=6; //3 static variable Hide the field definition of
static Variable in class A.

public static void staticMethod(){//4 static method. Hides the definition of


static method in class A

System.out.println("staticMethod () in B");

Skarifahmed@gmail.com
56

public class HidingExample {

public static void main(String[] args) {

A aObj = new B();

aObj.staticMethod();//invoke static method of class A

System.out.println(“The Out put is”+ aObj.i);

Since (staticMethod()) it's a class method, the compiler and JVM don't expect
to need an actual instance to invoke the method. The compiler will only look
at the declared type of the reference, and use that declared type to
determine, at compile time, which method to call. Since aObj is declared as
type A, the compiler looks at aObj.staticMethod() and decides it means
A.staticMethod. It doesn't matter that the instance reffered to by aObj is
actually a B - for static methods, the compiler only uses the declared type of
the reference.

Override a static method, what that means is that even if you write code that
looks like it's overriding a static method - it won't behave like an overridden
method.

The declaration of staticVariable in class B hides the definition of staticVariable


in class A, so class B does not inherit the field static Variable from its super
class A.

b) Given classes A, B, and C, where B extends A, and C extends B, and


where all classes implement the instance method void doIt(),static
method void doneIt() and declare a field member int BillType. How
can the instance method doIt() and static method doneIt() in A be
called from an instance method in C?How can the field member
BillType of class A be accessed from class C?

Ans :

Skarifahmed@gmail.com
57

class A {

public String BillType = "small bill"; //1

public void doIt() {//2

System.out.println("aDoIt");

public static void doneIt() {//3

System.out.println("aDoneIt");

class B extends A {

public String BillType = "mediam bill";//4 Hiding field

public void doIt() {//5 overridind instance method

System.out.println("aDoIt");

public static void doneIt() {//6 hide static method

System.out.println("aDoneIt");

public class C extends B {

public String BillType = "large bill";//7 Hiding field

public void doIt() {{//8 overridind instance method

System.out.println("aDoIt");

Skarifahmed@gmail.com
58

public static void doneIt() {{//9 hidind static method

System.out.println("aDoneIt");

void instanceMethod() {

((A) this).doIt();//10 invokes method at 8

System.out.println(((A) this).BillType); //11 invokes field at 1

((A) this).doneIt();//12 invokes static method at 3

public static void main(String arg[]) {

C c = new C();

c.instanceMethod();

All members(except non static method)defined in the class A, are accessible in


the context of an instance method in C. The reason is that all instance
methods are passed an implicit reference to the current object, that is, the
object on which the method is being invoked. The current object can be
referenced in the body of the instance method by the keyword this. In the
body of the method, the this reference can be used like any other object
reference to access members of the object. In fact, the keyword this can be
used in any non-static context. The this reference can be used as a normal
reference to reference the current object, but the reference cannot be
modified.

The this reference to the current object is useful in situations where a local
variable hides, ors hadows, a field with the same name.

Skarifahmed@gmail.com
59

The this reference is available in non-static code and refers to the current
object. When an instance method is invoked, theth is reference denotes the
object on which the method is called.The field billType and static method
doneIt() from class A is accessed successfully by casting the this reference,
because it is the type of the reference that determines the field accessed.
From non-static code in a subclass, it is possible to directly access fields in a
class higher up the inheritance hierarchy, by casting the this reference.

c) What is the significance of this and super keyword? Give a piece of


code which shows the use of super and this keyword.

Ans:

this Used to represent an instance of the class in which it appears. this can
be used to access class members and as a reference to the current instance.
The this keyword is also used to forward a call from one constructor in a class
to another constructor in the same class.

public class Numbers {

private int aNumber = 42;

public int returnANumber() {

return this.aNumber;

//Current class instance can be used with variables

public int returnANumber(int intIn) {

return (intIn * this.returnANumber());

//Current class instance can be used with methods

public static void main(String[] args) {

Skarifahmed@gmail.com
60

Numbers numberTest = new Numbers();

System.out.println("The Number is " + numberTest.returnANumber());

//output is: The Number is 42

System.out.println("The Number is " +numberTest.returnANumber(2));

//output is: The Number is 84

Super Used to access members of a class inherited by the class in which it


appears. Allows a subclass to access overridden methods and hidden
members of its superclass. The super keyword is also used to forward a call
from a constructor to a constructor in the superclass.

Also used to specify a lower bound on a type parameter in Generics

class Cat {

public String name;

public Cat() {

name = "no nameIn";

public Cat(String nameIn) {

name = nameIn;

public String getName() {

return (name + " the Cat");

Skarifahmed@gmail.com
61

public class Himalayan extends Cat {

public Himalayan() {

public Himalayan(String nameIn) {

name = nameIn;

public String getName() {

return (name + " the Himalayan");

public String getNameAsCat() {

return super.getName();

public static void main(String[] args) {

Himalayan cappuccino = new Himalayan("Cappuccino");

System.out.println("The Himalayan name is " +cappuccino.getName());

//output is: The Himalayan name is

//Cappuccino the Himalayan

System.out.println("The Cat name is " + cappuccino.getNameAsCat());

//output is: The Cat name is

// Cappuccino the Cat

Skarifahmed@gmail.com
62

d) What is Constructor chaining in java?How can you implement this


feature using super() and this() constructor? Explain with example.

Ans :

Every constructor calls its superclass constructor. An implied super() is


therefore included in each constructor which does not include either the this()
function or an explicit super() call as its first statement. The super()
statement invokes a constructor of the super class.

The implicit super() can be replaced by an explicit super(). The super


statement must be the first statement of the constructor.

The explicit super allows parameter values to be passed to the constructor of


its superclass and must have matching parameter types A super() call in the
constructor of a subclass will result in the call of the relevant constructor from
the superclass, based on the signature of the call. This is called constructor
chaining.

Below is an example of a class demonstrating constructor chaining using


super() method.

class Cube {

int length;

int breadth;

int height;

public int getVolume() {

return (length * breadth * height);

Cube() {

this(10, 10);

Skarifahmed@gmail.com
63

System.out.println("Finished with Default Constuctor of Cube");

Cube(int l, int b) {

this(l, b, 10);

System.out.println("Finished with Parametrized Constuctor having 2


params of Cube");

Cube(int l, int b, int h) {

length = l;

breadth = b;

height = h;

System.out.println("Finished with Parametrized Constuctor having 3


params of Cube");

public class SpecialCube extends Cube {

int weight;

SpecialCube() {

super();

weight = 10;

SpecialCube(int l, int b) {

this(l, b, 10);

Skarifahmed@gmail.com
64

System.out.println("Finished with Parametrized Constuctor having 2


params of SpecialCube");

SpecialCube(int l, int b, int h) {

super(l, b, h);

weight = 20;

System.out.println("Finished with Parametrized Constuctor having 3


params of SpecialCube");

public static void main(String[] args) {

SpecialCube specialObj1 = new SpecialCube();

SpecialCube specialObj2 = new SpecialCube(10, 20);

System.out.println("Volume of SpecialCube1 is : " +


specialObj1.getVolume());

System.out.println("Weight of SpecialCube1 is : " + specialObj1.weight);

System.out.println("Volume of SpecialCube2 is : " +


specialObj2.getVolume());

System.out.println("Weight of SpecialCube2 is : " + specialObj2.weight);

Output & explanation:

Finished with Parametrized Constuctor having 3 params of Cube

Finished with Parametrized Constuctor having 2 params of Cube

Finished with Default Constuctor of Cube

Finished with Parametrized Constuctor having 3 params of Cube

Skarifahmed@gmail.com
65

Finished with Parametrized Constuctor having 3 params of SpecialCube

Finished with Parametrized Constuctor having 2 params of SpecialCube

Volume of SpecialCube1 is : 1000

Weight of SpecialCube1 is : 10

Volume of SpecialCube2 is : 2000

Weight of SpecialCube2 is : 20

The super() construct as with this() construct: if used, must occur as the first
statement in a constructor, and it can only be used in a constructor
declaration. This implies that this() and super() calls cannot both occur in the
same constructor. Just as the this() construct leads to chaining of constructors
in the same class, the super() construct leads to chaining of subclass
constructors to superclass constructors.

if a constructor has neither a this() nor a super() construct as its first


statement, then a super() call to the default constructor in the superclass is
inserted.

e) Specify the rules of reference value assignments/reference


casting. Explain by giving example.

Ans:

interface IStack { // (1)

void push(Object item);

Object pop();

interface ISafeStack extends IStack { // (5)

boolean isEmpty();

boolean isFull();

Skarifahmed@gmail.com
66

class StackImpl implements IStack { // (2)

protected Object[] stackArray;

protected int tos; // top of stack

public StackImpl(int capacity) {

stackArray = new Object[capacity];

tos = -1;

public void push(Object item) // (3)

stackArray[++tos] = item;

public Object pop() { // (4)

Object objRef = stackArray[tos];

stackArray[tos] = null;

tos--;

return objRef;

public Object peek() {

return stackArray[tos];

Skarifahmed@gmail.com
67

class SafeStackImpl extends StackImpl implements ISafeStack { // (6)

public SafeStackImpl(int capacity) {

super(capacity);

public boolean isEmpty() {

return tos < 0;

} // (7)

public boolean isFull() {

return tos >= stackArray.length - 1;

}// (8)

public class ReferenceConversion {

public static void main(String[] args) {

// Reference declarations

Object objRef;

StackImpl stackRef;

SafeStackImpl safeStackRef;

IStack iStackRef;

ISafeStack iSafeStackRef;

// SourceType is a class type

safeStackRef = new SafeStackImpl(10);

objRef = safeStackRef;// (1) Always possible

Skarifahmed@gmail.com
68

stackRef = safeStackRef;// (2) Subclass to superclass assignment

iStackRef = stackRef; // (3) StackImpl implements IStack

iSafeStackRef = safeStackRef;// (4) SafeStackImpl implements


ISafeStack

// SourceType is an interface type

objRef = iStackRef; // (5) Always possible

iStackRef = iSafeStackRef; // (6) Sub- to super-interface assignment

// SourceType is an array type.

Object[] objArray = new Object[3];

StackImpl[] stackArray = new StackImpl[3];

SafeStackImpl[] safeStackArray = new SafeStackImpl[5];

ISafeStack[] iSafeStackArray = new ISafeStack[5];

int[] intArray = new int[10];

// Reference value assignments

objRef = objArray; // (7) Always possible

objRef = stackArray; // (8) Always possible

objArray = stackArray; // (9) Always possible

objArray = iSafeStackArray;// (10) Always possible

objRef = intArray; // (11) Always possible

// objArray = intArray; // (12) Compile-time error

stackArray = safeStackArray; // (13) Subclass array to superclass array

iSafeStackArray =

safeStackArray; // (14) SafeStackImpl implements ISafeStack

Skarifahmed@gmail.com
69

// Parameter Conversion

System.out.println("First call:");

sendParams(stackRef, safeStackRef, iStackRef,

safeStackArray, iSafeStackArray); // (15)

// Call Signature: sendParams(StackImpl, SafeStackImpl, IStack,

// SafeStackImpl[], ISafeStack[]);

System.out.println("Second call:");

sendParams(iSafeStackArray, stackRef, iSafeStackRef,

stackArray, safeStackArray); // (16)

// Call Signature: sendParams(ISafeStack[], StackImpl, ISafeStack,

// StackImpl[], SafeStackImpl[]);

public static void sendParams(Object objRefParam, StackImpl


stackRefParam,

IStack iStackRefParam, StackImpl[] stackArrayParam,

final IStack[] iStackArrayParam) { // (17)

// Signature: sendParams(Object, StackImpl, IStack, StackImpl[], IStack[])

// Print class name of object denoted by the reference at runtime.

System.out.println(objRefParam.getClass());

System.out.println(stackRefParam.getClass());

System.out.println(iStackRefParam.getClass());

System.out.println(stackArrayParam.getClass());

System.out.println(iStackArrayParam.getClass());

Skarifahmed@gmail.com
70

If an assignment is legal, then the reference value of srcRef is said to be


assignable (or assignment compatible) to the reference of

DestinationType. The rules are illustrated by concrete cases from example


above.

Rule1 If SourceType is a class type, then the reference value in srcRef may be
assigned to the destRef reference, provided
DestinationType is one of the following:
DestinationType is a superclass of the subclass SourceType.
DestinationType is an interface type that is implemented by the class
SourceType.
objRef = safeStackRef; // (1) Always possible
stackRef = safeStackRef; // (2) Subclass to superclass assignment
iStackRef = stackRef; // (3) StackImpl implements IStack
iSafeStackRef = safeStackRef; // (4) SafeStackImpl implements ISafeStack

Rule2 If SourceType is an interface type, then the reference value in srcRef


may be assigned to the destRef reference, provided
DestinationType is one of the following:
DestinationType is Object.
DestinationType is a superinterface of subinterface SourceType.
objRef = iStackRef; // (5) Always possible
iStackRef = iSafeStackRef; // (6) Subinterface to superinterface assignment

Rule3 If SourceType is an array type, then the reference value in srcRef may
be assigned to the destRef reference, provided
DestinationType is one of the following:
DestinationType is Object.
DestinationType is an array type, where the element type of SourceType is
assignable to the element type of
DestinationType.
objRef = objArray; // (7) Always possible
objRef = stackArray; // (8) Always possible
objArray = stackArray; // (9) Always possible
objArray = iSafeStackArray;// (10) Always possible
objRef = intArray; // (11) Always possible
// objArray = intArray; // (12) Compile-time error

Skarifahmed@gmail.com
71

stackArray = safeStackArray; // (13) Subclass array to superclass array


iSafeStackArray =
safeStackArray; // (14) SafeStackImpl implements ISafeStack

The rules for assignment are enforced at compile time, guaranteeing that no
type conversion error will occur during assignment at
runtime. Such conversions are type safe. The reason the rules can be
enforced at compile time is that they concern the type of the
reference (which is always known at compile time) rather than the actual type
of the object being referenced (which is known at runtime).

f) What is the significance of instanceOf and cast operator?Explain by


giving example.

Ans:

Instanceof operator:- Instanceof expression returns a Boolean value


indicating whether or not the specified object is an instance of the specified
type (class). It returns false if object is not an instance of the specified class,
or if object is null.

It is of the following general form:

<object> instanceof <class>

Eg.-

public class MainClass {

public static void main(String[] a) {

String s = "Hello";

if (s instanceof java.lang.String) {

System.out.println("is a String");

Skarifahmed@gmail.com
72

Cast operator:-

The cast operator (type) is used to convert numeric values from one numeric
type to another or to change an object reference to a compatible type used to
enable conversions that would normally be disallowed by the compiler .

Eg.-

byte a = 1;

byte b = 2;

byte c = a + b; // a and b are promoted to int

byte c = (byte)(a + b);

g) What is the difference between inheritance and aggregation?


Which one depicts ‘is-a’ and ‘has-a’ relationship? Explain by giving
example.

Ans:

Inheritance: Inheritance is the inclusion of behavior and state of a base class


in a derived class so that they are accessible in that derived class. The key
benefit of Inheritance is that it provides the formal mechanism for code reuse.

Additional property of inheritance: propagation of attributes and methods

Inheritance provides: is-a relationship;

Aggregation: Aggregation is an association in which one class belongs to a


collection. This is a part of a whole relationship where a part can exist without
a whole.

Properties of aggregation: transitivity, antisymmetry

Aggregation provides: has-a relationship;

Skarifahmed@gmail.com
73

The ‘is a’ relationship is expressed with inheritance and ‘has a’ relationship is


expressed with aggregation. Both inheritance and aggregation allow you to
place sub-objects inside your new class. Two of the main techniques for

Inheritance is unidirectional. For example House is a Building. But Building is


not a House. Inheritance uses extends key word. Aggregation: is used when
House has a Bathroom. It is incorrect to say House is a Bathroom.
Aggregation simply means using instance variables that refer to other objects.
The class House will have an instance variable, which refers to a Bathroom
object.

Skarifahmed@gmail.com
74

Nested Class And Interface


a) What is inner class? How many types of inner classes are there?
Give example of each.

An inner class is a non static nested class that is defined within the definition
of another class but outside any member definition. Inner classes should not
be marked static.

There are three categories of inner classes

1. Member classes(non-static member classes)

2. Local classes

3. Anonymous classes

Member classes :-A member class is a class that is defined inside the
definition of another class, (without the use of the static modifier as is the
case with a nested top-level class).

Example:

Skarifahmed@gmail.com
75

public class Nest {


private String var = "foo";

private class Nested {


public Nested() {
var = "bar";
}
}
}

Local classes - Local classes are like local variables, specific to a block of code.
Their visibility is only within the block of their declaration. In order for the
class to be useful beyond the declaration block, it would need to implement
amore publicly available interface. Because local classes are not members, the
modifiers public, protected, private, and static are not usable.

Example:

Enumeration myEnumerate(final Object array[]) {


class E implements Enumeration {
int count = 0;
public boolean hasMoreElements()
{ return count < array.length; }
public Object nextElement()
{ return array[count++]; }
}
return new E();
}

Anonymous classes - Anonymous inner classes extend local inner classes one
level further. As anonymous classes have no name, you cannot provide a
constructor.

Example :

button.addActionListener(new ActionListener() {
// This is how you define an anonymous inner class
public void actionPerformed(ActionEvent e) {

Skarifahmed@gmail.com
76

System.out.println("The button was pressed!");


}
});

b)Why the static inner classes are not considered as in the category of
inner classes? How can a interface be defined as a member of a class?

Ans:

A static member class is defined as a static member in a class or an interface.


Such a nested class can be instantiated like any ordinary top-level class, using
its full name. No enclosing instance is required to instantiate a static member
class.

Nested interfaces are considered implicitly static, the keyword static can,
therefore, be omitted. Since static member classes and interfaces are
members of an enclosing class or interface, they can have any member
accessibility.

public class TopLevelClass {


public static class StaticMemberClass_1 {
// ...
private interface StaticMemberInterface_1_1 {
// ...
}
public static class StaticMemberClass_1_1 implements
StaticMemberInterface_1 {
// ...
}
}
interface StaticMemberInterface_1 extends
StaticMemberClass_1.StaticMemberInterface_1_1 {
// ...
}
}

class AnotherTopLevelClass implements


TopLevelClass.StaticMemberInterface_1 {
// instantiate a static inner class
TopLevelClass.StaticMemberClass_1.StaticMemberClass_1_1 objRef1 =
new TopLevelClass.StaticMemberClass_1.StaticMemberClass_1_1();

Skarifahmed@gmail.com
77

c) Write about the accessibility modifier of the following member


classes.

i) Static member class ii) Non Static member class

iii) Local class in static and nonstatic context

iv) Anonymous class in static and nonstatic context

Ans:

5.d) Write about the direct accessibility of enclosing context of the


following member classes.i)Static member class ii)Non Static
member classiii)Local class in static and non static context

iv)Anonymous class in static and non static context

Ans:

Skarifahmed@gmail.com
78

Skarifahmed@gmail.com
79

e) Write about the declaration in entity body of the following member


classes.

i)Static member class ii)Non Static member class

iii)Local class in static and nonstatic context

iv)Anonymous class in static and nonstatic context

Ans:

f) What about the association of the enclosing instance with the outer
instance for the following member classes.

i) Static member class ii) Non Static member class

iii) Local class in static and nonstatic context

iv) Anonymous class in static and nonstatic context

Ans:

Skarifahmed@gmail.com
80

g)Assume that there is a Top level Class Outer1.Inside Outer1 another


non static member class Inner 1 is declared.

Inside the Inner1 class another non static member class Inner2 is
declared. These three classes contain a instance member name of
type String. How can the instance member of Outer1 be accessed
from Inner2?

Ans.

class Outer1

private String id = "Outer1 object ";

public Outer1(String objId) { id = id + objId; }

public void printId() {

System.out.println(id);

Skarifahmed@gmail.com
81

class Inner1

private String id = "Inner1 object ";

public Inner1(String objId) { id = id + objId; }

public void printId() {

System.out.print(Outer1.this.id + " : ");

System.out.println(id);

class Inner2 {

private String id = "Inner2 object ";

public Inner2(String objId) { id = id + objId; }

public void printId() {

System.out.print(Outer1.this.id + " : ");

System.out.println(id);

public void printIndividualIds() {

Outer1.this.printId();

Inner1.this.printId();

printId();

Skarifahmed@gmail.com
82

public class OuterCheck

public static void main(String[] args)

Outer1 a = new Outer1("a");

Outer1.Inner1 b = a.new Inner1("b");

b.printId();

Outer1.Inner1.Inner2 c = b.new Inner2("c");

c.printId();

Outer1.Inner1.Inner2 d = b.new Inner2("d");

d.printId();

Outer1.Inner1 bb = new Outer1("aa").new Inner1("bb");

bb.printId();

Outer1.Inner1.Inner2 cc = bb.new Inner2("cc");

cc.printId();

Outer1.Inner1.Inner2 ccc =new Outer1("aaa").new Inner1("bbb").new


Inner2("ccc");

ccc.printId();//accessing the superclass Outer1 using subclass Inner2.

System.out.println("------------");

ccc.printIndividualIds();

Skarifahmed@gmail.com
83

Output:

Outer1 object a : Inner1 object b

Outer1 object a : Inner2 object c

Outer1 object a : Inner2 object d

Outer1 object aa : Inner1 object bb

Outer1 object aa : Inner2 object cc

Outer1 object aaa : Inner2 object ccc

------------

Outer1 object aaa

Outer1 object aaa : Inner1 object bbb

Outer1 object aaa : Inner2 object ccc

h)What is the difference between anonymous class and local class?

Ans.

Local class : A local class is declared inside a method, a constructor, a static


initializer, or an instance initializer. A local class cannot have a static modifier.
A local class is analogous to a local variable in some ways. You cannot use
public, protected, private, or static modifiers in a local class analogous to a
local variable.

Anonymous class : Anonymous class is a class defined inside a method


without a name and is instantiated and declared in the same place.
Anonymous classes do not allow the use of extends and implements clauses
and access modifiers. An anonymous class doesn't have constructors, and it is
not allowed to define a constructor

Eg. Of Anonymous class:

Skarifahmed@gmail.com
84

interface Foo { void print(); }

class LocalClassTest

public static void main(String[] args) {

Foo foo = getFooImpl(100);

foo.print();

public static Foo getFooImpl(final int i) {

return new Foo() {

public void print() {

System.out.println("i = " + i);

};

Eg. Of Local class:

interface Foo { void print(); }

class LocalClassTest

public static void main(String[] args) {

Foo foo = getFooImpl(100);

foo.print();

}public static Foo getFooImpl(final int i) {

Skarifahmed@gmail.com
85

class FooImpl implements Foo {

public void print() {

System.out.println("i = " + i);

}return new FooImpl();

Skarifahmed@gmail.com

You might also like