612

The Complete Placement Guide- 2nd Edition

Embed Size (px)

Citation preview

© Copyright : IT Engg Portal – www.itportal.in 1

“Knowledge is your possession ,The more you Share

The more you Earn! ”

Lets Share Knowledge! – IT Engg Portal

© Copyright : IT Engg Portal – www.itportal.in 2

Contents

C++ Interview Questions ............................................................................................................................................5

C++ Object-Oriented Interview Questions And Answers .................................................................................... 35

C++ programming on UNIX ............................................................................................................................... 45

C++ Networking Interview Questions and Answers ............................................................................................ 47

C++ Algorithm Interview Questions and Answers .............................................................................................. 48

Java Interview Questions and Answers ................................................................................................................... 51

JDBC Interview Questions and Answers .............................................................................................................. 144

Servlet Interview Questions and Answers ............................................................................................................. 229

Data Structures Interview Questions and Answers ............................................................................................... 234

Networking Interview Questions and Answers ........................................................................................................ 245

Operating System Interview Questions and Answers ............................................................................................ 267

Linux Interview Questions and Answers ............................................................................................................... 275

Unix Interview Questions and Answers ................................................................................................................... 292

Manual Testing Interview Questions and Answers ............................................................................................... 314

Microprocessor Interview Questions and Answers .................................................................................................. 341

Oracle Interview Questions and Answers ............................................................................................................. 348

C Aptitude Questions ............................................................................................................................................. 517

Bibliography .......................................................................................................................................................... 610

Material referenced from : ................................................................................................................................... 610

© Copyright : IT Engg Portal – www.itportal.in 3

Preface After the huge success of our E-guide : ‗The Complete Placement Guide‘, we

would now like to bring to you the Second Revised Edition of ‗The Complete

Placement Guide 2012‘. With the overwhelming response of the first edition (with

over 5000+ downloads) the demand for the revised edition was on high. A lot of

students had requested an update for the revised edition as the campus placements in

majority colleges will be commencing soon.

In our second edition, we have included a few subjects which was not covered in the

prior version, like – Servlets, Testing, Microprocessors, Linux and Unix based

Interview Questions. With our guides students would not require any more references

for technical preparation. The guide covers all possible subjects for Technical Aptitude

and interviews in campus placements.‘The Complete Placement Guide ‘ is a

complete book for technical preparation. The presentation of the contents of this guide

is in a lucid format and hence none of you would face any difficulty in understanding

the contents of this guide.

If you find any errors in our guide or you would like to give us any suggestion, we

would be glad to hear it from you. Please feel free to contact us on our forum or you

can directly mail to us at [email protected].

Finally, our team expresses our sincere gratitude to 5 main websites for referencing

the contents requires for this guide namely- www.techpreparation.com,

www.indiabix.com , www.stackoverflow.com, www.roseindia.com and

www.geekinterview.com .

Regards -

Team : IT Engg Portal

© Copyright : IT Engg Portal – www.itportal.in 4

C++

Interview

Questions

&

Answers

© Copyright : IT Engg Portal – www.itportal.in 5

C++ Interview Questions

What is C++?

Released in 1985, C++ is an object-oriented programming language created by Bjarne

Stroustrup. C++ maintains almost all aspects of the C language, while simplifying

memory management and adding several features - including a new datatype known as

a class (you will learn more about these later) - to allow object-oriented programming.

C++ maintains the features of C which allowed for low-level memory access but also

gives the programmer new tools to simplify memory management.

C++ used for:

C++ is a powerful general-purpose programming language. It can be used to create

small programs or large applications. It can be used to make CGI scripts or console-

only DOS programs. C++ allows you to create programs to do almost anything you

need to do. The creator of C++, Bjarne Stroustrup, has put together a partial list of

applications written in C++.

How do you find out if a linked-list has an end? (i.e. the list is not a cycle)

You can find out by using 2 pointers. One of them goes 2 nodes each time. The second

one goes at 1 nodes each time. If there is a cycle, the one that goes 2 nodes each time

will eventually meet the one that goes slower. If that is the case, then you will know

the linked-list is a cycle.

What is the difference between realloc() and free()?

The free subroutine frees a block of memory previously allocated by the malloc

subroutine. Undefined results occur if the Pointer parameter is not a valid pointer. If

the Pointer parameter is a null value, no action will occur. The realloc subroutine

changes the size of the block of memory pointed to by the Pointer parameter to the

number of bytes specified by the Size parameter and returns a new pointer to the

block. The pointer specified by the Pointer parameter must have been created with the

© Copyright : IT Engg Portal – www.itportal.in 6

malloc, calloc, or realloc subroutines and not been deallocated with the free or realloc

subroutines. Undefined results occur if the Pointer parameter is not a valid pointer.

What is function overloading and operator overloading?

Function overloading: C++ enables several functions of the same name to be defined,

as long as these functions have different sets of parameters (at least as far as their

types are concerned). This capability is called function overloading. When an

overloaded function is called, the C++ compiler selects the proper function by

examining the number, types and order of the arguments in the call. Function

overloading is commonly used to create several functions of the same name that

perform similar tasks but on different data types.

Operator overloading allows existing C++ operators to be redefined so that they work

on objects of user-defined classes. Overloaded operators are syntactic sugar for

equivalent function calls. They form a pleasant facade that doesn't add anything

fundamental to the language (but they can improve understandability and reduce

maintenance costs).

What is the difference between declaration and definition?

The declaration tells the compiler that at some later point we plan to present the

definition of this declaration.

E.g.: void stars () //function declaration

The definition contains the actual implementation.

E.g.: void stars () // declarator

{

for(int j=10; j > =0; j--) //function body

cout << *;

cout << endl; }

What are the advantages of inheritance? It permits code reusability. Reusability saves time in program development. It

© Copyright : IT Engg Portal – www.itportal.in 7

encourages the reuse of proven and debugged high-quality software, thus reducing

problem after a system becomes functional.

How do you write a function that can reverse a linked-list?

void reverselist(void)

{

if(head==0)

return;

if(head->next==0)

return;

if(head->next==tail)

{

head->next = 0;

tail->next = head;

}

else

{

node* pre = head;

node* cur = head->next;

node* curnext = cur->next;

head->next = 0;

cur-> next = head;

for(; curnext!=0; )

{

cur->next = pre;

pre = cur;

cur = curnext;

curnext = curnext->next;

}

curnext->next = cur;

}

}

© Copyright : IT Engg Portal – www.itportal.in 8

What do you mean by inline function?

The idea behind inline functions is to insert the code of a called function at the point

where the function is called. If done carefully, this can improve the application's

performance in exchange for increased compile time and possibly (but not always) an

increase in the size of the generated binary executables.

Write a program that ask for user input from 5 to 9 then calculate the average #include "iostream.h"

int main() {

int MAX = 4;

int total = 0;

int average;

int numb;

for (int i=0; i<MAX; i++) {

cout << "Please enter your input between 5 and 9: ";

cin >> numb;

while ( numb<5 || numb>9) {

cout << "Invalid input, please re-enter: ";

cin >> numb;

}

total = total + numb;

}

average = total/MAX;

cout << "The average number is: " << average << "\n";

return 0;

}

Write a short code using C++ to print out all odd number from 1 to 100 using a

for loop for( unsigned int i = 1; i < = 100; i++ )

if( i & 0x00000001 )

cout << i << \",\";

What is public, protected, private?

Public, protected and private are three access specifier in C++.

Public data members and member functions are accessible outside the class.

© Copyright : IT Engg Portal – www.itportal.in 9

Protected data members and member functions are only available to derived classes.

Private data members and member functions can‘t be accessed outside the class.

However there is an exception can be using friend classes.

Write a function that swaps the values of two integers, using int* as the argument

type.

void swap(int* a, int*b) {

int t;

t = *a;

*a = *b;

*b = t;

}

Tell how to check whether a linked list is circular. Create two pointers, each set to the start of the list. Update each as follows:

while (pointer1) {

pointer1 = pointer1->next;

pointer2 = pointer2->next; if (pointer2) pointer2=pointer2->next;

if (pointer1 == pointer2) {

print (\"circular\n\");

}

}

OK, why does this work? If a list is circular, at some point pointer2 will wrap around and be either at the item

just before pointer1, or the item before that. Either way, it‘s either 1 or 2 jumps until

they meet.

What is virtual constructors/destructors?

Answer1 Virtual destructors:

If an object (with a non-virtual destructor) is destroyed explicitly by applying the

delete operator to a base-class pointer to the object, the base-class destructor function

(matching the pointer type) is called on the object.

© Copyright : IT Engg Portal – www.itportal.in 10

There is a simple solution to this problem declare a virtual base-class destructor.

This makes all derived-class destructors virtual even though they don‘t have the same

name as the base-class destructor. Now, if the object in the hierarchy is destroyed

explicitly by applying the delete operator to a base-class pointer to a derived-class

object, the destructor for the appropriate class is called. Virtual constructor:

Constructors cannot be virtual. Declaring a constructor as a virtual function is a syntax

error.

Answer2

Virtual destructors: If an object (with a non-virtual destructor) is destroyed explicitly

by applying the delete operator to a base-class pointer to the object, the base-class

destructor function (matching the pointer type) is called on the object.

There is a simple solution to this problem – declare a virtual base-class destructor.

This makes all derived-class destructors virtual even though they don‘t have the same

name as the base-class destructor. Now, if the object in the hierarchy is destroyed

explicitly by applying the delete operator to a base-class pointer to a derived-class

object, the destructor for the appropriate class is called.

Virtual constructor: Constructors cannot be virtual. Declaring a constructor as a

virtual function is a syntax error. Does c++ support multilevel and multiple

inheritance? Yes.

What are the advantages of inheritance? • It permits code reusability.

• Reusability saves time in program development.

• It encourages the reuse of proven and debugged high-quality software, thus reducing

problem after a system becomes functional.

What is the difference between declaration and definition? The declaration tells the compiler that at some later point we plan to present the

definition of this declaration.

E.g.: void stars () //function declaration

The definition contains the actual implementation.

E.g.: void stars () // declarator

{

for(int j=10; j>=0; j--) //function body

© Copyright : IT Engg Portal – www.itportal.in 11

cout<<‖*‖;

cout<<endl; }

What is the difference between an ARRAY and a LIST?

Answer1

Array is collection of homogeneous elements.

List is collection of heterogeneous elements.

For Array memory allocated is static and continuous.

For List memory allocated is dynamic and Random.

Array: User need not have to keep in track of next memory allocation.

List: User has to keep in Track of next location where memory is allocated.

Answer2

Array uses direct access of stored members, list uses sequencial access for members.

//With Array you have direct access to memory position 5

Object x = a[5]; // x takes directly a reference to 5th element of array

//With the list you have to cross all previous nodes in order to get the 5th node:

list mylist;

list::iterator it;

for( it = list.begin() ; it != list.end() ; it++ )

{

if( i==5)

{

x = *it;

break;

}

i++;

}

Does c++ support multilevel and multiple inheritance? Yes.

© Copyright : IT Engg Portal – www.itportal.in 12

What is a template? Templates allow to create generic functions that admit any data type as parameters and

return value without having to overload the function with all the possible data types.

Until certain point they fulfill the functionality of a macro. Its prototype is any of the

two following ones:

template <class indetifier> function_declaration; template <typename indetifier>

function_declaration;

The only difference between both prototypes is the use of keyword class or typename,

its use is indistinct since both expressions have exactly the same meaning and behave

exactly the same way.

Define a constructor - What it is and how it might be called (2 methods).

Answer1

constructor is a member function of the class, with the name of the function being the

same as the class name. It also specifies how the object should be initialized.

Ways of calling constructor:

1) Implicitly: automatically by complier when an object is created.

2) Calling the constructors explicitly is possible, but it makes the code unverifiable.

Answer2

class Point2D{

int x; int y;

public Point2D() : x(0) , y(0) {} //default (no argument) constructor

};

main(){

Point2D MyPoint; // Implicit Constructor call. In order to allocate memory on stack,

the default constructor is implicitly called.

Point2D * pPoint = new Point2D(); // Explicit Constructor call. In order to allocate

memory on HEAP we call the default constructor.

© Copyright : IT Engg Portal – www.itportal.in 13

You have two pairs: new() and delete() and another pair : alloc() and free().

Explain differences between eg. new() and malloc() Answer1

1.) ―new and delete‖ are preprocessors while ―malloc() and free()‖ are functions. [we

dont use brackets will calling new or delete].

2.) no need of allocate the memory while using ―new‖ but in ―malloc()‖ we have to

use ―sizeof()‖.

3.) ―new‖ will initlize the new memory to 0 but ―malloc()‖ gives random value in the

new alloted memory location [better to use calloc()]

Answer2

new() allocates continous space for the object instace

malloc() allocates distributed space.

new() is castless, meaning that allocates memory for this specific type,

malloc(), calloc() allocate space for void * that is cated to the specific class type

pointer.

What is the difference between class and structure? Structure: Initially (in C) a structure was used to bundle different type of data types

together to perform a particular functionality. But C++ extended the structure to

contain functions also. The major difference is that all declarations inside a structure

are by default public.

Class: Class is a successor of Structure. By default all the members inside the class are

private.

What is RTTI?

Runtime type identification (RTTI) lets you find the dynamic type of an object when

you have only a pointer or a reference to the base type. RTTI is the official way in

standard C++ to discover the type of an object and to convert the type of a pointer or

reference (that is, dynamic typing). The need came from practical experience with

C++. RTTI replaces many Interview Questions - Homegrown versions with a solid,

consistent approach.

© Copyright : IT Engg Portal – www.itportal.in 14

What is encapsulation? Packaging an object‘s variables within its methods is called encapsulation.

Explain term POLIMORPHISM and give an example using eg. SHAPE object: If

I have a base class SHAPE, how would I define DRAW methods for two objects

CIRCLE and SQUARE

Answer1

POLYMORPHISM : A phenomenon which enables an object to react differently to

the same function call.

in C++ it is attained by using a keyword virtual

Example

public class SHAPE

{

public virtual void SHAPE::DRAW()=0;

}

Note here the function DRAW() is pure virtual which means the sub classes must

implement the DRAW() method and SHAPE cannot be instatiated

public class CIRCLE::public SHAPE

{

public void CIRCLE::DRAW()

{

// TODO drawing circle

}

}

public class SQUARE::public SHAPE

{

public void SQUARE::DRAW()

{

// TODO drawing square

}

}

now from the user class the calls would be like

globally

SHAPE *newShape;

© Copyright : IT Engg Portal – www.itportal.in 15

When user action is to draw

public void MENU::OnClickDrawCircle(){

newShape = new CIRCLE();

}

public void MENU::OnClickDrawCircle(){

newShape = new SQUARE();

}

the when user actually draws

public void CANVAS::OnMouseOperations(){

newShape->DRAW();

}

Answer2

class SHAPE{

public virtual Draw() = 0; //abstract class with a pure virtual method

};

class CIRCLE{

public int r;

public virtual Draw() { this->drawCircle(0,0,r); }

};

class SQURE

public int a;

public virtual Draw() { this->drawRectangular(0,0,a,a); }

};

Each object is driven down from SHAPE implementing Draw() function in its own

way.

© Copyright : IT Engg Portal – www.itportal.in 16

What is an object? Object is a software bundle of variables and related methods. Objects have state and

behavior.

How can you tell what shell you are running on UNIX system? You can do the Echo $RANDOM. It will return a undefined variable if you are from

the C-Shell, just a return prompt if you are from the Bourne shell, and a 5 digit random

numbers if you are from the Korn shell. You could also do a ps -l and look for the

shell with the highest PID.

What do you mean by inheritance? Inheritance is the process of creating new classes, called derived classes, from existing

classes or base classes. The derived class inherits all the capabilities of the base class,

but can add embellishments and refinements of its own.

Describe PRIVATE, PROTECTED and PUBLIC – the differences and give

examples.

class Point2D{

int x; int y;

public int color;

protected bool pinned;

public Point2D() : x(0) , y(0) {} //default (no argument) constructor

};

Point2D MyPoint;

You cannot directly access private data members when they are declared (implicitly)

private:

MyPoint.x = 5; // Compiler will issue a compile ERROR

//Nor yoy can see them:

int x_dim = MyPoint.x; // Compiler will issue a compile ERROR

On the other hand, you can assign and read the public data members:

MyPoint.color = 255; // no problem

© Copyright : IT Engg Portal – www.itportal.in 17

int col = MyPoint.color; // no problem

With protected data members you can read them but not write them: MyPoint.pinned =

true; // Compiler will issue a compile ERROR

bool isPinned = MyPoint.pinned; // no problem

What is namespace? Namespaces allow us to group a set of global classes, objects and/or functions under a

name. To say it somehow, they serve to split the global scope in sub-scopes known as

namespaces.

The form to use namespaces is:

namespace identifier { namespace-body }

Where identifier is any valid identifier and namespace-body is the set of classes,

objects and functions that are included within the namespace. For example:

namespace general { int a, b; } In this case, a and b are normal variables integrated

within the general namespace. In order to access to these variables from outside the

namespace we have to use the scope operator ::. For example, to access the previous

variables we would have to put:

general::a general::b

The functionality of namespaces is specially useful in case that there is a possibility

that a global object or function can have the same name than another one, causing a

redefinition error.

What is a COPY CONSTRUCTOR and when is it called? A copy constructor is a method that accepts an object of the same class and copies it‘s

data members to the object on the left part of assignement:

class Point2D{

int x; int y;

public int color;

protected bool pinned;

public Point2D() : x(0) , y(0) {} //default (no argument) constructor

public Point2D( const Point2D & ) ;

};

© Copyright : IT Engg Portal – www.itportal.in 18

Point2D::Point2D( const Point2D & p )

{

this->x = p.x;

this->y = p.y;

this->color = p.color;

this->pinned = p.pinned;

}

main(){

Point2D MyPoint;

MyPoint.color = 345;

Point2D AnotherPoint = Point2D( MyPoint ); // now AnotherPoint has color = 345

What is Boyce Codd Normal form? A relation schema R is in BCNF with respect to a set F of functional dependencies if

for all functional dependencies in F+ of the form a-> , where a and b is a subset of R,

at least one of the following holds:

* a- > b is a trivial functional dependency (b is a subset of a)

* a is a superkey for schema R

What is virtual class and friend class? Friend classes are used when two or more classes are designed to work together and

need access to each other's implementation in ways that the rest of the world shouldn't

be allowed to have. In other words, they help keep private things private. For instance,

it may be desirable for class DatabaseCursor to have more privilege to the internals of

class Database than main() has.

What is the word you will use when defining a function in base class to allow this

function to be a polimorphic function? virtual

What do you mean by binding of data and functions? Encapsulation.

What are 2 ways of exporting a function from a DLL?

1.Taking a reference to the function from the DLL instance.

2. Using the DLL ‘s Type Library

© Copyright : IT Engg Portal – www.itportal.in 19

What is the difference between an object and a class? Classes and objects are separate but related concepts. Every object belongs to a class

and every class contains one or more related objects.

- A Class is static. All of the attributes of a class are fixed before, during, and after the

execution of a program. The attributes of a class don't change.

- The class to which an object belongs is also (usually) static. If a particular object

belongs to a certain class at the time that it is created then it almost certainly will still

belong to that class right up until the time that it is destroyed.

- An Object on the other hand has a limited lifespan. Objects are created and

eventually destroyed. Also during that lifetime, the attributes of the object may

undergo significant change.

Suppose that data is an array of 1000 integers. Write a single function call that

will sort the 100 elements data [222] through data [321]. quicksort ((data + 222), 100);

What is a class? Class is a user-defined data type in C++. It can be created to solve a particular kind of

problem. After creation the user need not know the specifics of the working of a class.

What is friend function? As the name suggests, the function acts as a friend to a class. As a friend of a class, it

can access its private and protected members. A friend function is not a member of the

class. But it must be listed in the class definition.

Which recursive sorting technique always makes recursive calls to sort subarrays

that are about half size of the original array? Mergesort always makes recursive calls to sort subarrays that are about half size of the

original array, resulting in O(n log n) time.

What is abstraction? Abstraction is of the process of hiding unwanted details from the user.

What are virtual functions? A virtual function allows derived classes to replace the implementation provided by

the base class. The compiler makes sure the replacement is always called whenever the

© Copyright : IT Engg Portal – www.itportal.in 20

object in question is actually of the derived class, even if the object is accessed by a

base pointer rather than a derived pointer. This allows algorithms in the base class to

be replaced in the derived class, even if users don't know about the derived class.

What is the difference between an external iterator and an internal iterator?

Describe an advantage of an external iterator. An internal iterator is implemented with member functions of the class that has items

to step through. .An external iterator is implemented as a separate class that can be

"attach" to the object that has items to step through. .An external iterator has the

advantage that many difference iterators can be active simultaneously on the same

object.

What is a scope resolution operator? A scope resolution operator (::), can be used to define the member functions of a class

outside the class.

What do you mean by pure virtual functions? A pure virtual member function is a member function that the base class forces derived

classes to provide. Normally these member functions have no implementation. Pure

virtual functions are equated to zero.

class Shape { public: virtual void draw() = 0; };

What is polymorphism? Explain with an example? "Poly" means "many" and "morph" means "form". Polymorphism is the ability of an

object (or reference) to assume (be replaced by) or become many different forms of

object.

Example: function overloading, function overriding, virtual functions. Another

example can be a plus ‗+‘ sign, used for adding two integers or for using it to

concatenate two strings.

What‟s the output of the following program? Why?

#include <stdio.h>

main()

{

© Copyright : IT Engg Portal – www.itportal.in 21

typedef union

{

int a;

char b[10];

float c;

}

Union;

Union x,y = {100};

x.a = 50;

strcpy(x.b,\"hello\");

x.c = 21.50;

printf(\"Union x : %d %s %f \n\",x.a,x.b,x.c );

printf(\"Union y :%d %s%f \n\",y.a,y.b,y.c);

}

Given inputs X, Y, Z and operations | and & (meaning bitwise OR and AND,

respectively)

What is output equal to in

output = (X & Y) | (X & Z) | (Y & Z)

Why are arrays usually processed with for loop? The real power of arrays comes from their facility of using an index variable to

traverse the array, accessing each element with the same expression a[i]. All the is

needed to make this work is a iterated statement in which the variable i serves as a

counter, incrementing from 0 to a.length -1. That is exactly what a loop does.

What is an HTML tag? Answer: An HTML tag is a syntactical construct in the HTML language that

abbreviates specific instructions to be executed when the HTML script is loaded into a

Web browser. It is like a method in Java, a function in C++, a procedure in Pascal, or a

subroutine in FORTRAN.

© Copyright : IT Engg Portal – www.itportal.in 22

Explain which of the following declarations will compile and what will be

constant - a pointer or the value pointed at: * const char *

* char const *

* char * const

Note: Ask the candidate whether the first declaration is pointing to a string or a single

character. Both explanations are correct, but if he says that it‘s a single character

pointer, ask why a whole string is initialized as char* in C++. If he says this is a string

declaration, ask him to declare a pointer to a single character. Competent candidates

should not have problems pointing out why const char* can be both a character and a

string declaration, incompetent ones will come up with invalid reasons.

You‟re given a simple code for the class Bank Customer. Write the following

functions:

* Copy constructor

* = operator overload

* == operator overload

* + operator overload (customers‟ balances should be added up, as an example of

joint account between husband and wife)

Note:Anyone confusing assignment and equality operators should be dismissed from

the interview. The applicant might make a mistake of passing by value, not by

reference. The candidate might also want to return a pointer, not a new object, from

the addition operator. Slightly hint that you‘d like the value to be changed outside the

function, too, in the first case. Ask him whether the statement customer3 = customer1

+ customer2 would work in the second case.

What problems might the following macro bring to the application? #define sq(x) x*x

Anything wrong with this code?

T *p = new T[10];

delete p;

© Copyright : IT Engg Portal – www.itportal.in 23

Everything is correct, Only the first element of the array will be deleted‖, The entire

array will be deleted, but only the first element destructor will be called.

Anything wrong with this code?

T *p = 0;

delete p;

Yes, the program will crash in an attempt to delete a null pointer.

How do you decide which integer type to use? It depends on our requirement. When we are required an integer to be stored in 1 byte

(means less than or equal to 255) we use short int, for 2 bytes we use int, for 8 bytes

we use long int.

A char is for 1-byte integers, a short is for 2-byte integers, an int is generally a 2-byte

or 4-byte integer (though not necessarily), a long is a 4-byte integer, and a long long is

a 8-byte integer.

What does extern mean in a function declaration?

Using extern in a function declaration we can make a function such that it can used

outside the file in which it is defined.

An extern variable, function definition, or declaration also makes the described

variable or function usable by the succeeding part of the current source file. This

declaration does not replace the definition. The declaration is used to describe the

variable that is externally defined.

If a declaration for an identifier already exists at file scope, any extern declaration of

the same identifier found within a block refers to that same object. If no other

declaration for the identifier exists at file scope, the identifier has external linkage.

What can I safely assume about the initial values of variables which are not

explicitly initialized? It depends on complier which may assign any garbage value to a variable if it is not

initialized.

© Copyright : IT Engg Portal – www.itportal.in 24

What is the difference between char a[] = “string”; and char *p = “string”;? In the first case 6 bytes are allocated to the variable a which is fixed, where as in the

second case if *p is assigned to some other value the allocate memory can change.

What‟s the auto keyword good for?

Answer1

Not much. It declares an object with automatic storage duration. Which means the

object will be destroyed at the end of the objects scope. All variables in functions that

are not declared as static and not dynamically allocated have automatic storage

duration by default.

For example

int main()

{

int a; //this is the same as writing ―auto int a;‖

}

Answer2

Local variables occur within a scope; they are ―local‖ to a function. They are often

called automatic variables because they automatically come into being when the scope

is entered and automatically go away when the scope closes. The keyword auto makes

this explicit, but local variables default to auto auto auto auto so it is never necessary

to declare something as an auto auto auto auto.

What is the difference between char a[] = “string”; and char *p = “string”; ?

Answer1 a[] = ―string‖;

char *p = ―string‖;

The difference is this:

p is pointing to a constant string, you can never safely say

p[3]=‘x';

however you can always say a[3]=‘x';

char a[]=‖string‖; - character array initialization.

char *p=‖string‖ ; - non-const pointer to a const-string.( this is permitted only in the

case of char pointer in C++ to preserve backward compatibility with C.)

© Copyright : IT Engg Portal – www.itportal.in 25

Answer2 a[] = ―string‖;

char *p = ―string‖;

a[] will have 7 bytes. However, p is only 4 bytes. P is pointing to an adress is either

BSS or the data section (depending on which compiler — GNU for the former and CC

for the latter).

Answer3 char a[] = ―string‖;

char *p = ―string‖;

for char a[]…….using the array notation 7 bytes of storage in the static memory block

are taken up, one for each character and one for the terminating nul character.

But, in the pointer notation char *p………….the same 7 bytes required, plus N bytes

to store the pointer variable ―p‖ (where N depends on the system but is usually a

minimum of 2 bytes and can be 4 or more)……

How do I declare an array of N pointers to functions returning pointers to

functions returning pointers to characters?

Answer1 If you want the code to be even slightly readable, you will use typedefs.

typedef char* (*functiontype_one)(void);

typedef functiontype_one (*functiontype_two)(void);

functiontype_two myarray[N]; //assuming N is a const integral

Answer2 - pto

char* (* (*a[N])())()

Here a is that array. And according to question no function will not take any parameter

value.

What does extern mean in a function declaration? It tells the compiler that a variable or a function exists, even if the compiler hasn‘t yet

seen it in the file currently being compiled. This variable or function may be defined in

another file or further down in the current file.

© Copyright : IT Engg Portal – www.itportal.in 26

How do I initialize a pointer to a function?

This is the way to initialize a pointer to a function

void fun(int a)

{

}

void main()

{

void (*fp)(int);

fp=fun;

fp(1);

}

How do you link a C++ program to C functions? By using the extern "C" linkage specification around the C function declarations.

Explain the scope resolution operator. It permits a program to reference an identifier in the global scope that has been hidden

by another identifier with the same name in the local scope.

What are the differences between a C++ struct and C++ class? The default member and base-class access specifier are different.

How many ways are there to initialize an int with a constant? Two.

There are two formats for initializers in C++ as shown in the example that follows.

The first format uses the traditional C notation. The second format uses constructor

notation.

int foo = 123;

int bar (123);

How does throwing and catching exceptions differ from using setjmp and

longjmp? The throw operation calls the destructors for automatic objects instantiated since entry

to the try block.

© Copyright : IT Engg Portal – www.itportal.in 27

What is a default constructor? Default constructor WITH arguments class B { public: B (int m = 0) : n (m) {} int n;

}; int main(int argc, char *argv[]) { B b; return 0; }

What is a conversion constructor? A constructor that accepts one argument of a different type.

What is the difference between a copy constructor and an overloaded assignment

operator? A copy constructor constructs a new object by using the content of the argument

object. An overloaded assignment operator assigns the contents of an existing object to

another existing object of the same class.

When should you use multiple inheritance? There are three acceptable answers: "Never," "Rarely," and "When the problem

domain cannot be accurately modeled any other way."

Explain the ISA and HASA class relationships. How would you implement each

in a class design? A specialized class "is" a specialization of another class and, therefore, has the ISA

relationship with the other class. An Employee ISA Person. This relationship is best

implemented with inheritance. Employee is derived from Person. A class may have an

instance of another class. For example, an employee "has" a salary, therefore the

Employee class has the HASA relationship with the Salary class. This relationship is

best implemented by embedding an object of the Salary class in the Employee class.

When is a template a better solution than a base class? When you are designing a generic class to contain or otherwise manage objects of

other types, when the format and behavior of those other types are unimportant to their

containment or management, and particularly when those other types are unknown

(thus, the generosity) to the designer of the container or manager class.

What is a mutable member? One that can be modified by the class even when the object of the class or the member

function doing the modification is const.

What is an explicit constructor? A conversion constructor declared with the explicit keyword. The compiler does not

© Copyright : IT Engg Portal – www.itportal.in 28

use an explicit constructor to implement an implied conversion of types. It‘s purpose is

reserved explicitly for construction.

What is the Standard Template Library (STL)?

A library of container templates approved by the ANSI committee for inclusion in the

standard C++ specification.

A programmer who then launches into a discussion of the generic programming

model, iterators, allocators, algorithms, and such, has a higher than average

understanding of the new technology that STL brings to C++ programming.

Describe run-time type identification. The ability to determine at run time the type of an object by using the typeid operator

or the dynamic_cast operator.

What problem does the namespace feature solve? Multiple providers of libraries might use common global identifiers causing a name

collision when an application tries to link with two or more such libraries. The

namespace feature surrounds a library‘s external declarations with a unique namespace

that eliminates the potential for those collisions.

This solution assumes that two library vendors don‘t use the same namespace

identifier, of course.

Are there any new intrinsic (built-in) data types? Yes. The ANSI committee added the bool intrinsic type and its true and false value

keywords.

Will the following program execute? void main()

{

void *vptr = (void *) malloc(sizeof(void));

vptr++;

}

Answer1

It will throw an error, as arithmetic operations cannot be performed on void pointers.

© Copyright : IT Engg Portal – www.itportal.in 29

Answer2

It will not build as sizeof cannot be applied to void* ( error ―Unknown size‖ )

Answer3 How can it execute if it won‘t even compile? It needs to be int main, not void main.

Also, cannot increment a void *.

Answer4 According to gcc compiler it won‘t show any error, simply it executes. but in general

we can‘t do arthematic operation on void, and gives size of void as 1

Answer5 The program compiles in GNU C while giving a warning for ―void main‖. The

program runs without a crash. sizeof(void) is ―1? hence when vptr++, the address is

incremented by 1.

Answer6 Regarding arguments about GCC, be aware that this is a C++ question, not C. So gcc

will compile and execute, g++ cannot. g++ complains that the return type cannot be

void and the argument of sizeof() cannot be void. It also reports that ISO C++ forbids

incrementing a pointer of type ‗void*‘.

Answer7 in C++

voidp.c: In function `int main()‘:

voidp.c:4: error: invalid application of `sizeof‘ to a void type

voidp.c:4: error: `malloc‘ undeclared (first use this function)

voidp.c:4: error: (Each undeclared identifier is reported only once for each function it

appears in.)

voidp.c:6: error: ISO C++ forbids incrementing a pointer of type `void*‘

But in c, it work without problems

void main()

{

© Copyright : IT Engg Portal – www.itportal.in 30

char *cptr = 0?2000;

long *lptr = 0?2000;

cptr++;

lptr++;

printf(” %x %x”, cptr, lptr);

}

Will it execute or not?

Answer1 For Q2: As above, won‘t compile because main must return int. Also, 0×2000 cannot

be implicitly converted to a pointer (I assume you meant 0×2000 and not 0?2000.)

Answer2 Not Excute.

Compile with VC7 results following errors:

error C2440: ‗initializing‘ : cannot convert from ‗int‘ to ‗char *‘

error C2440: ‗initializing‘ : cannot convert from ‗int‘ to ‗long *‘

Not Excute if it is C++, but Excute in C.

The printout:

2001 2004

Answer3 In C++

[$]> g++ point.c

point.c: In function `int main()‘:

point.c:4: error: invalid conversion from `int‘ to `char*‘

point.c:5: error: invalid conversion from `int‘ to `long int*‘

in C

———————————–

[$] etc > gcc point.c

point.c: In function `main‘:

point.c:4: warning: initialization makes pointer from integer without a cast

point.c:5: warning: initialization makes pointer from integer without a cast

© Copyright : IT Engg Portal – www.itportal.in 31

[$] etc > ./a.exe

2001 2004

What is the difference between Mutex and Binary semaphore?

semaphore is used to synchronize processes. where as mutex is used to provide

synchronization between threads running in the same process.

In C++, what is the difference between method overloading and method

overriding? Overloading a method (or function) in C++ is the ability for functions of the same

name to be defined as long as these methods have different signatures (different set of

parameters). Method overriding is the ability of the inherited class rewriting the virtual

method of the base class.

What methods can be overridden in Java? In C++ terminology, all public methods in Java are virtual. Therefore, all Java

methods can be overwritten in subclasses except those that are declared final, static,

and private.

What are the defining traits of an object-oriented language? The defining traits of an object-oriented langauge are:

* encapsulation

* inheritance

* polymorphism

Write a program that ask for user input from 5 to 9 then calculate the average int main()

{

int MAX=4;

int total =0;

int average=0;

int numb;

cout<<"Please enter your input from 5 to 9";

cin>>numb;

if((numb <5)&&(numb>9))

cout<<"please re type your input";

else

for(i=0;i<=MAX; i++)

© Copyright : IT Engg Portal – www.itportal.in 32

{

total = total + numb;

average= total /MAX;

}

cout<<"The average number is"<<average<<endl;

return 0;

}

Assignment Operator - What is the diffrence between a "assignment operator"

and a "copy constructor"? Answer1.

In assignment operator, you are assigning a value to an existing object. But in copy

constructor, you are creating a new object and then assigning a value to that object.

For example:

complex c1,c2;

c1=c2; //this is assignment

complex c3=c2; //copy constructor

Answer2.

A copy constructor is used to initialize a newly declared variable from an existing

variable. This makes a deep copy like assignment, but it is somewhat simpler:

There is no need to test to see if it is being initialized from itself.

There is no need to clean up (eg, delete) an existing value (there is none).

A reference to itself is not returned.

RTTI - What is RTTI? Answer1.

RTTI stands for "Run Time Type Identification". In an inheritance hierarchy, we can

find out the exact type of the objet of which it is member. It can be done by using:

1) dynamic id operator

2) typecast operator

© Copyright : IT Engg Portal – www.itportal.in 33

Answer2.

RTTI is defined as follows: Run Time Type Information, a facility that allows an

object to be queried at runtime to determine its type. One of the fundamental

principles of object technology is polymorphism, which is the ability of an object to

dynamically change at runtime.

STL Containers - What are the types of STL containers? There are 3 types of STL containers:

1. Adaptive containers like queue, stack

2. Associative containers like set, map

3. Sequence containers like vector, deque

What is the need for a Virtual Destructor ? Destructors are declared as virtual because if do not declare it as virtual the base class

destructor will be called before the derived class destructor and that will lead to

memory leak because derived class’s objects will not get freed.Destructors are

declared virtual so as to bind objects to the methods at runtime so that appropriate

destructor is called.

What is "mutable"?

Answer1.

"mutable" is a C++ keyword. When we declare const, none of its data members can

change. When we want one of its members to change, we declare it as mutable.

Answer2.

A "mutable" keyword is useful when we want to force a "logical const" data member

to have its value modified. A logical const can happen when we declare a data member

as non-const, but we have a const member function attempting to modify that data

member. For example:

class Dummy {

public:

bool isValid() const;

private:

mutable int size_ = 0;

mutable bool validStatus_ = FALSE;

// logical const issue resolved

© Copyright : IT Engg Portal – www.itportal.in 34

};

bool Dummy::isValid() const

// data members become bitwise const

{

if (size > 10) {

validStatus_ = TRUE; // fine to assign

size = 0; // fine to assign

}

}

Answer2.

"mutable" keyword in C++ is used to specify that the member may be updated or

modified even if it is member of constant object. Example:

class Animal {

private:

string name;

string food;

mutable int age;

public:

void set_age(int a);

};

void main() {

const Animal Tiger(’Fulffy’,'antelope’,1);

Tiger.set_age(2);

// the age can be changed since its mutable

}

Differences of C and C++

Could you write a small program that will compile in C but not in C++ ? In C, if you can a const variable e.g.

const int i = 2;

you can use this variable in other module as follows

extern const int i;

C compiler will not complain.

© Copyright : IT Engg Portal – www.itportal.in 35

But for C++ compiler u must write

extern const int i = 2;

else error would be generated.

Bitwise Operations - Given inputs X, Y, Z and operations | and & (meaning

bitwise OR and AND, respectively), what is output equal to in? output = (X & Y) | (X & Z) | (Y & Z);

C++ Object-Oriented Interview Questions And Answers

What is a modifier? A modifier, also called a modifying function is a member function that changes the

value of at least one data member. In other words, an operation that modifies the state

of an object. Modifiers are also known as ‗mutators‘. Example: The function mod is a

modifier in the following code snippet:

class test

{

int x,y;

public:

test()

{

x=0; y=0;

}

void mod()

{

x=10;

y=15;

}

};

© Copyright : IT Engg Portal – www.itportal.in 36

What is an accessor? An accessor is a class operation that does not modify the state of an object. The

accessor functions need to be declared as const operations

Differentiate between a template class and class template.

Template class: A generic definition or a parameterized class not instantiated until the

client provides the needed information. It‘s jargon for plain templates. Class template:

A class template specifies how individual classes can be constructed much like the

way a class specifies how individual objects can be constructed. It‘s jargon for plain

classes.

When does a name clash occur? A name clash occurs when a name is defined in more than one place. For example.,

two different class libraries could give two different classes the same name. If you try

to use many class libraries at the same time, there is a fair chance that you will be

unable to compile or link the program because of name clashes.

Define namespace. It is a feature in C++ to minimize name collisions in the global name space. This

namespace keyword assigns a distinct name to a library that allows other libraries to

use the same identifier names without creating any name collisions. Furthermore, the

compiler uses the namespace signature for differentiating the definitions.

What is the use of „using‟ declaration. ? A using declaration makes it possible to use a name from a namespace without the

scope operator.

What is an Iterator class ? A class that is used to traverse through the objects maintained by a container class.

There are five categories of iterators: input iterators, output iterators, forward iterators,

bidirectional iterators, random access. An iterator is an entity that gives access to the

contents of a container object without violating encapsulation constraints. Access to

the contents is granted on a one-at-a-time basis in order. The order can be storage

order (as in lists and queues) or some arbitrary order (as in array indices) or according

to some ordering relation (as in an ordered binary tree). The iterator is a construct,

which provides an interface that, when called, yields either the next element in the

container, or some value denoting the fact that there are no more elements to examine.

Iterators hide the details of access to and update of the elements of a container class.

© Copyright : IT Engg Portal – www.itportal.in 37

The simplest and safest iterators are those that permit read-only access to the contents

of a container class.

What is an incomplete type? Incomplete types refers to pointers in which there is non availability of the

implementation of the referenced location or it points to some location whose value is

not available for modification.

int *i=0x400 // i points to address 400

*i=0; //set the value of memory location pointed by i.

Incomplete types are otherwise called uninitialized pointers.

What is a dangling pointer? A dangling pointer arises when you use the address of an object after

its lifetime is over. This may occur in situations like returning

addresses of the automatic variables from a function or using the

address of the memory block after it is freed. The following

code snippet shows this:

class Sample

{

public:

int *ptr;

Sample(int i)

{

ptr = new int(i);

}

~Sample()

{

delete ptr;

}

void PrintVal()

{

cout << "The value is " << *ptr;

}

© Copyright : IT Engg Portal – www.itportal.in 38

};

void SomeFunc(Sample x)

{

cout << "Say i am in someFunc " << endl;

}

int main()

{

Sample s1 = 10;

SomeFunc(s1);

s1.PrintVal();

}

In the above example when PrintVal() function is

called it is called by the pointer that has been freed by the

destructor in SomeFunc.

Differentiate between the message and method.

Message:

* Objects communicate by sending messages to each other.

* A message is sent to invoke a method.

Method

* Provides response to a message.

* It is an implementation of an operation.

What is an adaptor class or Wrapper class? A class that has no functionality of its own. Its member functions hide the use of a

third party software component or an object with the non-compatible interface or a

non-object-oriented implementation.

What is a Null object? It is an object of some class whose purpose is to indicate that a real object of that class

does not exist. One common use for a null object is a return value from a member

function that is supposed to return an object with some specified properties but cannot

find such an object.

© Copyright : IT Engg Portal – www.itportal.in 39

What is class invariant? A class invariant is a condition that defines all valid states for an object. It is a logical

condition to ensure the correct working of a class. Class invariants must hold when an

object is created, and they must be preserved under all operations of the class. In

particular all class invariants are both preconditions and post-conditions for all

operations or member functions of the class.

What do you mean by Stack unwinding? It is a process during exception handling when the destructor is called for all local

objects between the place where the exception was thrown and where it is caught.

Define precondition and post-condition to a member function. Precondition: A precondition is a condition that must be true on entry to a member

function. A class is used correctly if preconditions are never false. An operation is not

responsible for doing anything sensible if its precondition fails to hold. For example,

the interface invariants of stack class say nothing about pushing yet another element

on a stack that is already full. We say that isful() is a precondition of the push

operation. Post-condition: A post-condition is a condition that must be true on exit

from a member function if the precondition was valid on entry to that function. A class

is implemented correctly if post-conditions are never false. For example, after pushing

an element on the stack, we know that isempty() must necessarily hold. This is a post-

condition of the push operation.

What are the conditions that have to be met for a condition to be an invariant of

the class? * The condition should hold at the end of every constructor.

* The condition should hold at the end of every mutator (non-const) operation.

What are proxy objects? Objects that stand for other objects are called proxy objects or surrogates.

template <class t="">

class Array2D

{

public:

class Array1D

{

public:

T& operator[] (int index);

© Copyright : IT Engg Portal – www.itportal.in 40

const T& operator[] (int index)const;

};

Array1D operator[] (int index);

const Array1D operator[] (int index) const;

};

The following then becomes legal:

Array2D<float>data(10,20);

cout<<data[3][6]; // fine

Here data[3] yields an Array1D object and the operator [] invocation on that object

yields the float in position(3,6) of the original two dimensional array. Clients of the

Array2D class need not be aware of the presence of the Array1D class. Objects of this

latter class stand for one-dimensional array objects that, conceptually, do not exist for

clients of Array2D. Such clients program as if they were using real, live, two-

dimensional arrays. Each Array1D object stands for a one-dimensional array that is

absent from a conceptual model used by the clients of Array2D. In the above example,

Array1D is a proxy class. Its instances stand for one-dimensional arrays that,

conceptually, do not exist.

Name some pure object oriented languages. Smalltalk, Java, Eiffel, Sather.

What is an orthogonal base class? If two base classes have no overlapping methods or data they are said to be

independent of, or orthogonal to each other. Orthogonal in the sense means that two

classes operate in different dimensions and do not interfere with each other in any

way. The same derived class may inherit such classes with no difficulty.

What is a node class?

A node class is a class that,

* relies on the base class for services and implementation,

* provides a wider interface to the users than its base class,

* relies primarily on virtual functions in its public interface

* depends on all its direct and indirect base class

© Copyright : IT Engg Portal – www.itportal.in 41

* can be understood only in the context of the base class

* can be used as base for further derivation

* can be used to create objects.

A node class is a class that has added new services or functionality beyond the

services inherited from its base class.

What is a container class? What are the types of container classes? A container class is a class that is used to hold objects in memory or external storage.

A container class acts as a generic holder. A container class has a predefined behavior

and a well-known interface. A container class is a supporting class whose purpose is to

hide the topology used for maintaining the list of objects in memory. When a container

class contains a group of mixed objects, the container is called a heterogeneous

container; when the container is holding a group of objects that are all the same, the

container is called a homogeneous container.

How do you write a function that can reverse a linked-list? Answer1:

void reverselist(void)

{

if(head==0)

return;

if(head-<next==0)

return;

if(head-<next==tail)

{

head-<next = 0;

tail-<next = head;

}

else

{

node* pre = head;

node* cur = head-<next;

node* curnext = cur-<next;

head-<next = 0;

cur-<next = head;

© Copyright : IT Engg Portal – www.itportal.in 42

for(; curnext!=0; )

{

cur-<next = pre;

pre = cur;

cur = curnext;

curnext = curnext-<next;

}

curnext-<next = cur;

}

}

Answer2:

node* reverselist(node* head)

{

if(0==head || 0==head->next)

//if head->next ==0 should return head instead of 0;

return 0;

{

node* prev = head;

node* curr = head->next;

node* next = curr->next;

for(; next!=0; )

{

curr->next = prev;

prev = curr;

curr = next;

next = next->next;

}

curr->next = prev;

head->next = 0;

head = curr;

}

© Copyright : IT Engg Portal – www.itportal.in 43

return head;

}

What is polymorphism? Polymorphism is the idea that a base class can be inherited by several classes. A base

class pointer can point to its child class and a base class array can store different child

class objects.

How do you find out if a linked-list has an end? (i.e. the list is not a cycle) You can find out by using 2 pointers. One of them goes 2 nodes each time. The second

one goes at 1 nodes each time. If there is a cycle, the one that goes 2 nodes each time

will eventually meet the one that goes slower. If that is the case, then you will know

the linked-list is a cycle.

How can you tell what shell you are running on UNIX system?

You can do the Echo $RANDOM. It will return a undefined variable if you are from

the C-Shell, just a return prompt if you are from the Bourne shell, and a 5 digit random

numbers if you are from the Korn shell. You could also do a ps -l and look for the

shell with the highest PID.

What is Boyce Codd Normal form? A relation schema R is in BCNF with respect to a set F of functional dependencies if

for all functional dependencies in F+ of the form a->b, where a and b is a subset of R,

at least one of the following holds:

* a->b is a trivial functional dependency (b is a subset of a)

* a is a superkey for schema R

What is pure virtual function? A class is made abstract by declaring one or more of its virtual functions to be pure. A

pure virtual function is one with an initializer of = 0 in its declaration

Write a Struct Time where integer m, h, s are its members struct Time

{

int m;

int h;

© Copyright : IT Engg Portal – www.itportal.in 44

int s;

};

How do you traverse a Btree in Backward in-order? Process the node in the right subtree

Process the root

Process the node in the left subtree

What is the two main roles of Operating System? As a resource manager

As a virtual machine

In the derived class, which data member of the base class are visible? In the public and protected sections.

© Copyright : IT Engg Portal – www.itportal.in 45

C++ programming on UNIX

Could you tell something about the Unix System Kernel? The kernel is the heart of the UNIX openrating system, it‘s reponsible for controlling

the computer‘s resouces and scheduling user jobs so that each one gets its fair share of

resources.

What are each of the standard files and what are they normally associated with? They are the standard input file, the standard output file and the standard error file.

The first is usually associated with the keyboard, the second and third are usually

associated with the terminal screen.

Detemine the code below, tell me exectly how many times is the operation sum++

performed ? for ( i = 0; i < 100; i++ )

for ( j = 100; j > 100 - i; j–)

sum++;

(99 * 100)/2 = 4950

The sum++ is performed 4950 times.

Give 4 examples which belongs application layer in TCP/IP architecture? FTP, TELNET, HTTP and TFTP

What‟s the meaning of ARP in TCP/IP? The "ARP" stands for Address Resolution Protocol. The ARP standard defines two

basic message types: a request and a response. a request message contains an IP

address and requests the corresponding hardware address; a replay contains both the IP

address, sent in the request, and the hardware address.

What is a Makefile? Makefile is a utility in Unix to help compile large programs. It helps by only

compiling the portion of the program that has been changed.

A Makefile is the file and make uses to determine what rules to apply. make is useful

for far more than compiling programs.

What is deadlock? Deadlock is a situation when two or more processes prevent each other from running.

© Copyright : IT Engg Portal – www.itportal.in 46

Example: if T1 is holding x and waiting for y to be free and T2 holding y and waiting

for x to be free deadlock happens.

What is semaphore?

Semaphore is a special variable, it has two methods: up and down. Semaphore

performs atomic operations, which means ones a semaphore is called it can not be

inturrupted.

The internal counter (= #ups - #downs) can never be negative. If you execute the

―down‖ method when the internal counter is zero, it will block until some other thread

calls the ―up‖ method. Semaphores are use for thread synchronization.

Is C an object-oriented language? C is not an object-oriented language, but limited object-oriented programming can be

done in C.

Name some major differences between C++ and Java. C++ has pointers; Java does not. Java is platform-independent; C++ is not. Java has

garbage collection; C++ does not. Java does have pointers. In fact all variables in Java

are pointers. The difference is that Java does not allow you to manipulate the

addresses of the pointer

© Copyright : IT Engg Portal – www.itportal.in 47

C++ Networking Interview Questions and Answers

What is the difference between Stack and Queue? Stack is a Last In First Out (LIFO) data structure.

Queue is a First In First Out (FIFO) data structure

Write a fucntion that will reverse a string. char *strrev(char *s)

{

int i = 0, len = strlen(s);

char *str;

if ((str = (char *)malloc(len+1)) == NULL)

/*cannot allocate memory */

err_num = 2;

return (str);

}

while(len)

str[i++]=s[–len];

str[i] = NULL;

return (str);

}

What is the software Life-Cycle? The software Life-Cycle are

1) Analysis and specification of the task

2) Design of the algorithms and data structures

3) Implementation (coding)

4) Testing

5) Maintenance and evolution of the system

6) Obsolescence

What is the difference between a Java application and a Java applet? The difference between a Java application and a Java applet is that a Java application

is a program that can be executed using the Java interpeter, and a JAVA applet can be

transfered to different networks and executed by using a web browser (transferable to

the WWW).

© Copyright : IT Engg Portal – www.itportal.in 48

Name 7 layers of the OSI Reference Model? -Application layer -Presentation layer

-Session layer -Transport layer

-Network layer -Data Link layer

-Physical layer

C++ Algorithm Interview Questions and Answers

What are the advantages and disadvantages of B-star trees over Binary trees?

Answer1

B-star trees have better data structure and are faster in search than Binary trees, but it‘s

harder to write codes for B-start trees.

Answer2

The major difference between B-tree and binary tres is that B-tree is a external data

structure and binary tree is a main memory data structure. The computational

complexity of binary tree is counted by the number of comparison operations at each

node, while the computational complexity of B-tree is determined by the disk I/O, that

is, the number of node that will be loaded from disk to main memory. The

comparision of the different values in one node is not counted.

Write the psuedo code for the Depth first Search.

dfs(G, v) //OUTLINE

Mark v as "discovered"

For each vertex w such that edge vw is in G:

If w is undiscovered:

dfs(G, w); that is, explore vw, visit w, explore from there as much as possible, and

backtrack from w to v. Otherwise:

"Check" vw without visiting w. Mark v as "finished".

© Copyright : IT Engg Portal – www.itportal.in 49

Describe one simple rehashing policy.

The simplest rehashing policy is linear probing. Suppose a key K hashes to location i.

Suppose other key occupies H[i]. The following function is used to generate

alternative locations:

rehash(j) = (j + 1) mod h

where j is the location most recently probed. Initially j = i, the hash code for K. Notice

that this version of rehash does not depend on K.

Describe Stacks and name a couple of places where stacks are useful.

A Stack is a linear structure in which insertions and deletions are always made at one

end, called the top. This updating policy is called last in, first out (LIFO). It is useful

when we need to check some syntex errors, such as missing parentheses.

Suppose a 3-bit sequence number is used in the selective-reject ARQ, what is the

maximum number of frames that could be transmitted at a time?

If a 3-bit sequence number is used, then it could distinguish 8 different frames. Since

the number of frames that could be transmitted at a time is no greater half the numner

of frames that could be distinguished by the sequence number, so at most 4 frames can

be transmitted at a time.

-x-x-x-x-x-x-x-x-x-x-x-x-x-xx-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-

© Copyright : IT Engg Portal – www.itportal.in 50

Java

Interview Questions

&

Answers

© Copyright : IT Engg Portal – www.itportal.in 51

Java Interview Questions and Answers

What is Collection API ?

The Collection API is a set of classes and interfaces that support operation on

collections of objects. These classes and interfaces are more flexible, more

powerful, and more regular than the vectors, arrays, and hashtables if effectively

replaces.

Example of classes: HashSet, HashMap, ArrayList, LinkedList, TreeSet and

TreeMap.

Example of interfaces: Collection, Set, List and Map.

Is Iterator a Class or Interface? What is its use? Answer: Iterator is an interface which is used to step through the elements of a

Collection.

What is similarities/difference between an Abstract class and Interface? Differences are as follows:

Interfaces provide a form of multiple inheritance. A class can extend only one

other class. Interfaces are limited to public methods and constants with no

implementation. Abstract classes can have a partial implementation, protected

parts, static methods, etc.

A Class may implement several interfaces. But in case of abstract class, a class

may extend only one abstract class. Interfaces are slow as it requires extra

indirection to to find corresponding method in in the actual class. Abstract classes

are fast.

Similarities:

Neither Abstract classes or Interface can be instantiated.

Java Interview Questions - How to define an Abstract class?

A class containing abstract method is called Abstract class. An Abstract class

can't be instantiated.

Example of Abstract class:

abstract class testAbstractClass {

protected String myString;

public String getMyString() {

return myString;

}

© Copyright : IT Engg Portal – www.itportal.in 52

public abstract string anyAbstractFunction();

}

How to define an Interface in Java ?

In Java Interface defines the methods but does not implement them. Interface can

include constants. A class that implements the interfaces is bound to implement

all the methods defined in Interface.

Emaple of Interface:

public interface sampleInterface {

public void functionOne();

public long CONSTANT_ONE = 1000;

}

If a class is located in a package, what do you need to change in the OS

environment to be able to use it?

You need to add a directory or a jar file that contains the package directories to

the CLASSPATH environment variable. Let's say a class Employee belongs to a

package com.xyz.hr; and is located in the file c:\dev\com\xyz\hr\Employee.java.

In this case, you'd need to add c:\dev to the variable CLASSPATH. If this class

contains the method main(), you could test it from a command prompt window as

follows:

c:\>java com.xyz.hr.Employee

How many methods in the Serializable interface? There is no method in the Serializable interface. The Serializable interface acts as

a marker, telling the object serialization tools that your class is serializable.

How many methods in the Externalizable interface?

There are two methods in the Externalizable interface. You have to implement

these two methods in order to make your class externalizable. These two methods

are readExternal() and writeExternal().

What is the difference between Serializalble and Externalizable interface? When you use Serializable interface, your class is serialized automatically by

default. But you can override writeObject() and readObject() two methods to

© Copyright : IT Engg Portal – www.itportal.in 53

control more complex object serailization process. When you use Externalizable

interface, you have a complete control over your class's serialization process.

What is a transient variable in Java? A transient variable is a variable that may not be serialized. If you don't want

some field to be serialized, you can mark that field transient or static.

Which containers use a border layout as their default layout? The Window, Frame and Dialog classes use a border layout as their default

layout.

How are Observer and Observable used?

Objects that subclass the Observable class maintain a list of observers. When an

Observable object is updated, it invokes the update() method of each of its

observers to notify the observers that it has changed state. The Observer interface

is implemented by objects that observe Observable objects.

What is Java?

Java is an object-oriented programming language developed initially by James

Gosling and colleagues at Sun Microsystems. The language, initially called Oak

(named after the oak trees outside Gosling's office), was intended to replace C++,

although the feature set better resembles that of Objective C. Java should not be

confused with JavaScript, which shares only the name and a similar C-like

syntax. Sun Microsystems currently maintains and updates Java regularly.

What does a well-written OO program look like? A well-written OO program exhibits recurring structures that promote abstraction,

flexibility, modularity and elegance.

Can you have virtual functions in Java? Yes, all functions in Java are virtual by default. This is actually a pseudo trick

question because the word "virtual" is not part of the naming convention in Java

(as it is in C++, C-sharp and VB.NET), so this would be a foreign concept for

someone who has only coded in Java. Virtual functions or virtual methods are

functions or methods that will be redefined in derived classes.

Jack developed a program by using a Map container to hold key/value pairs.

He wanted to make a change to the map. He decided to make a clone of the

© Copyright : IT Engg Portal – www.itportal.in 54

map in order to save the original data on side. What do you think of it? ?

If Jack made a clone of the map, any changes to the clone or the original map

would be seen on both maps, because the clone of Map is a shallow copy. So Jack

made a wrong decision.

What is more advisable to create a thread, by implementing a Runnable

interface or by extending Thread class?

Strategically speaking, threads created by implementing Runnable interface are

more advisable. If you create a thread by extending a thread class, you cannot

extend any other class. If you create a thread by implementing Runnable

interface, you save a space for your class to extend another class now or in future.

What is NullPointerException and how to handle it?

When an object is not initialized, the default value is null. When the following

things happen, the NullPointerException is thrown:

--Calling the instance method of a null object.

--Accessing or modifying the field of a null object.

--Taking the length of a null as if it were an array.

--Accessing or modifying the slots of null as if it were an array.

--Throwing null as if it were a Throwable value.

The NullPointerException is a runtime exception. The best practice is to catch

such exception even if it is not required by language design.

An application needs to load a library before it starts to run, how to code? One option is to use a static block to load a library before anything is called. For

example,

class Test {

static {

System.loadLibrary("path-to-library-file");

}

....

}

When you call new Test(), the static block will be called first before any

initialization happens. Note that the static block position may matter.

How could Java classes direct program messages to the system console, but

error messages, say to a file?

© Copyright : IT Engg Portal – www.itportal.in 55

The class System has a variable out that represents the standard output, and the

variable err that represents the standard error device. By default, they both point

at the system console. This how the standard output could be re-directed:

Stream st = new Stream(new FileOutputStream("output.txt")); System.setErr(st);

System.setOut(st);

What's the difference between an interface and an abstract class? An abstract class may contain code in method bodies, which is not allowed in an

interface. With abstract classes, you have to inherit your class from it and Java

does not allow multiple inheritance. On the other hand, you can implement

multiple interfaces in your class.

Name the containers which uses Border Layout as their default layout? Containers which uses Border Layout as their default are: window, Frame and

Dialog classes.

What do you understand by Synchronization? Synchronization is a process of controlling the access of shared resources by the

multiple threads in such a manner that only one thread can access one resource at

a time. In non synchronized multithreaded application, it is possible for one

thread to modify a shared object while another thread is in the process of using or

updating the object's value.

Synchronization prevents such type of data corruption.

E.g. Synchronizing a function:

public synchronized void Method1 () {

// Appropriate method-related code.

}

E.g. Synchronizing a block of code inside a function:

public myFunction (){

synchronized (this) {

// Synchronized code here.

}

}

What is synchronization and why is it important?

With respect to multithreading, synchronization is the capability to control the

access of multiple threads to shared resources. Without synchronization, it is

possible for one thread to modify a shared object while another thread is in the

© Copyright : IT Engg Portal – www.itportal.in 56

process of using or updating that object's value. This often causes dirty data and

leads to significant errors.

What are synchronized methods and synchronized statements? Synchronized methods are methods that are used to control access to a method or

an object. A thread only executes a synchronized method after it has acquired the

lock for the method's object or class. Synchronized statements are similar to

synchronized methods. A synchronized statement can only be executed after a

thread has acquired the lock for the object or class referenced in the synchronized

statement.

What are three ways in which a thread can enter the waiting state? A thread can enter the waiting state by invoking its sleep() method, by blocking

on IO, by unsuccessfully attempting to acquire an object's lock, or by invoking an

object's wait() method. It can also enter the waiting state by invoking its

(deprecated) suspend() method.

Can a lock be acquired on a class? Yes, a lock can be acquired on a class. This lock is acquired on the class's Class

object.

What's new with the stop(), suspend() and resume() methods in JDK 1.2? The stop(), suspend() and resume() methods have been deprecated in JDK 1.2.

What is the preferred size of a component?

The preferred size of a component is the minimum component size that will allow

the component to display normally.

What's the difference between J2SDK 1.5 and J2SDK 5.0? There's no difference, Sun Microsystems just re-branded this version.

What would you use to compare two String variables - the operator == or

the method equals()? I'd use the method equals() to compare the values of the Strings and the == to

check if two variables point at the same instance of a String object.

What is thread?

A thread is an independent path of execution in a system.

© Copyright : IT Engg Portal – www.itportal.in 57

What is multi-threading? Multi-threading means various threads that run in a system.

How does multi-threading take place on a computer with a single CPU? The operating system's task scheduler allocates execution time to multiple tasks.

By quickly switching between executing tasks, it creates the impression that tasks

execute sequentially.

How to create a thread in a program? You have two ways to do so. First, making your class "extends" Thread class.

Second, making your class "implements" Runnable interface. Put jobs in a run()

method and call start() method to start the thread.

Can Java object be locked down for exclusive use by a given thread?

Yes. You can lock an object by putting it in a "synchronized" block. The locked

object is inaccessible to any thread other than the one that explicitly claimed it.

Can each Java object keep track of all the threads that want to exclusively

access to it? Yes. Use Thread.currentThread() method to track the accessing thread.

Does it matter in what order catch statements for FileNotFoundException

and IOExceptipon are written? Yes, it does. The FileNoFoundException is inherited from the IOException.

Exception's subclasses have to be caught first.

What invokes a thread's run() method? After a thread is started, via its start() method of the Thread class, the JVM

invokes the thread's run() method when the thread is initially executed.

What is the purpose of the wait(), notify(), and notifyAll() methods?

The wait(),notify(), and notifyAll() methods are used to provide an efficient way

for threads to communicate each other.

What are the high-level thread states? The high-level thread states are ready, running, waiting, and dead.

© Copyright : IT Engg Portal – www.itportal.in 58

What is the difference between yielding and sleeping? When a task invokes its yield() method, it returns to the ready state. When a task

invokes its sleep() method, it returns to the waiting state.

What happens when a thread cannot acquire a lock on an object? If a thread attempts to execute a synchronized method or synchronized statement

and is unable to acquire an object's lock, it enters the waiting state until the lock

becomes available.

What is the difference between Process and Thread? A process can contain multiple threads. In most multithreading operating systems,

a process gets its own memory address space; a thread doesn't. Threads typically

share the heap belonging to their parent process. For instance, a JVM runs in a

single process in the host O/S. Threads in the JVM share the heap belonging to

that process; that's why several threads may access the same object. Typically,

even though they share a common heap, threads have their own stack space. This

is how one thread's invocation of a method is kept separate from another's. This is

all a gross oversimplification, but it's accurate enough at a high level. Lots of

details differ between operating systems. Process vs. Thread A program vs.

similar to a sequential program an run on its own vs. Cannot run on its own Unit

of allocation vs. Unit of execution Have its own memory space vs. Share with

others Each process has one or more threads vs. Each thread belongs to one

process Expensive, need to context switch vs. Cheap, can use process memory

and may not need to context switch More secure. One process cannot corrupt

another process vs. Less secure. A thread can write the memory used by another

thread

Can an inner class declared inside of a method access local variables of this

method?

It's possible if these variables are final.

What can go wrong if you replace &emp;&emp; with &emp; in the following

code: String a=null; if (a!=null && a.length()>10) {...} A single ampersand here would lead to a NullPointerException.

What is the Vector class? The Vector class provides the capability to implement a growable array of objects

© Copyright : IT Engg Portal – www.itportal.in 59

What modifiers may be used with an inner class that is a member of an outer

class? A (non-local) inner class may be declared as public, protected, private, static,

final, or abstract.

If a method is declared as protected, where may the method be accessed? A protected method may only be accessed by classes or interfaces of the same

package or by subclasses of the class in which it is declared.

What is an Iterator interface? The Iterator interface is used to step through the elements of a Collection.

How many bits are used to represent Unicode, ASCII, UTF-16, and UTF-8

characters? Unicode requires 16 bits and ASCII require 7 bits. Although the ASCII character

set uses only 7 bits, it is usually represented as 8 bits. UTF-8 represents characters

using 8, 16, and 18 bit patterns. UTF-16 uses 16-bit and larger bit patterns.

What's the main difference between a Vector and an ArrayList? Java Vector class is internally synchronized and ArrayList is not.

What are wrapped classes? Wrapped classes are classes that allow primitive types to be accessed as objects.

Does garbage collection guarantee that a program will not run out of

memory? No, it doesn't. It is possible for programs to use up memory resources faster than

they are garbage collected. It is also possible for programs to create objects that

are not subject to garbage collection.

What is the difference between preemptive scheduling and time slicing? Under preemptive scheduling, the highest priority task executes until it enters the

waiting or dead states or a higher priority task comes into existence. Under time

slicing, a task executes for a predefined slice of time and then reenters the pool of

ready tasks. The scheduler then determines which task should execute next, based

on priority and other factors.

Name Component subclasses that support painting ?

The Canvas, Frame, Panel, and Applet classes support painting.

© Copyright : IT Engg Portal – www.itportal.in 60

What is a native method? A native method is a method that is implemented in a language other than Java.

How can you write a loop indefinitely? for(;;)--for loop; while(true)--always true, etc.

Can an anonymous class be declared as implementing an interface and extending

a class? An anonymous class may implement an interface or extend a superclass, but may not

be declared to do both.

What is the purpose of finalization? The purpose of finalization is to give an unreachable object the opportunity to perform

any cleanup processing before the object is garbage collected.

When should the method invokeLater()be used?

This method is used to ensure that Swing components are updated through the event-

dispatching thread.

How many methods in Object class? This question is not asked to test your memory. It tests you how well you know Java.

Ten in total.

clone()

equals() & hashcode()

getClass()

finalize()

wait() & notify()

toString()

How does Java handle integer overflows and underflows? It uses low order bytes of the result that can fit into the size of the type allowed by the

operation.

What is the numeric promotion?

Numeric promotion is used with both unary and binary bitwise operators. This means

that byte, char, and short values are converted to int values before a bitwise operator is

applied.

If a binary bitwise operator has one long operand, the other operand is converted to a

© Copyright : IT Engg Portal – www.itportal.in 61

long value.

The type of the result of a bitwise operation is the type to which the operands have

been promoted. For example:

short a = 5;

byte b = 10;

long c = 15;

The type of the result of (a+b) is int, not short or byte. The type of the result of (a+c)

or (b+c) is long.

Is the numeric promotion available in other platform? Yes. Because Java is implemented using a platform-independent virtual machine,

bitwise operations always yield the same result, even when run on machines that use

radically different CPUs.

What is the difference between the Boolean & operator and the && operator? If an expression involving the Boolean & operator is evaluated, both operands are

evaluated. Then the & operator is applied to the operand. When an expression

involving the && operator is evaluated, the first operand is evaluated. If the first

operand returns a value of true then the second operand is evaluated. The && operator

is then applied to the first and second operands. If the first operand evaluates to false,

the evaluation of the second operand is skipped.

Operator & has no chance to skip both sides evaluation and && operator does. If

asked why, give details as above.

When is the ArithmeticException throwQuestion: What is the

GregorianCalendar class?

The GregorianCalendar provides support for traditional Western calendars.

What is the SimpleTimeZone class? The SimpleTimeZone class provides support for a Gregorian calendar.

How can a subclass call a method or a constructor defined in a superclass? Use the following syntax: super.myMethod(); To call a constructor of the superclass,

just write super(); in the first line of the subclass's constructor.

What is the Properties class? The properties class is a subclass of Hashtable that can be read from or written to a

stream. It also provides the capability to specify a set of default values to be used.

© Copyright : IT Engg Portal – www.itportal.in 62

What is the purpose of the Runtime class? The purpose of the Runtime class is to provide access to the Java runtime system.

What is the purpose of the System class?

The purpose of the System class is to provide access to system resources.

What is the purpose of the finally clause of a try-catch-finally statement? The finally clause is used to provide the capability to execute code no matter whether

or not an exception is thrown or caught.

What is the Locale class? The Locale class is used to tailor program output to the conventions of a particular

geographic, political, or cultural region.

What is an abstract method? An abstract method is a method whose implementation is deferred to a subclass. Or, a

method that has no implementation.

What is the difference between interface and abstract class? interface contains methods that must be abstract; abstract class may contain concrete

methods. interface contains variables that must be static and final; abstract class may

contain non-final and final variables. members in an interface are public by default,

abstract class may contain non-public members. interface is used to "implements";

whereas abstract class is used to "extends". interface can be used to achieve multiple

inheritance; abstract class can be used as a single inheritance. interface can "extends"

another interface, abstract class can "extends" another class and "implements" multiple

interfaces. interface is absolutely abstract; abstract class can be invoked if a main()

exists. interface is more flexible than abstract class because one class can only

"extends" one super class, but "implements" multiple interfaces. If given a choice, use

interface instead of abstract class.

What is a static method? A static method is a method that belongs to the class rather than any object of the class

and doesn't apply to an object or even require that any objects of the class have been

instantiated.

© Copyright : IT Engg Portal – www.itportal.in 63

What is a protected method?

A protected method is a method that can be accessed by any method in its package and

inherited by any subclass of its class.

What is the difference between a static and a non-static inner class? A non-static inner class may have object instances that are associated with instances of

the class's outer class. A static inner class does not have any object instances.

What is an object's lock and which object's have locks? An object's lock is a mechanism that is used by multiple threads to obtain

synchronized access to the object. A thread may execute a synchronized method of an

object only after it has acquired the object's lock. All objects and classes have locks. A

class's lock is acquired on the class's Class object.

When can an object reference be cast to an interface reference? An object reference can be cast to an interface reference when the object implements

the referenced interface.

What is the difference between a Window and a Frame? The Frame class extends Window to define a main application window that can have a

menu bar.

What is the difference between a Window and a Frame? Heavy weight components like Abstract Window Toolkit (AWT), depend on the local

windowing toolkit. For example, java.awt.Button is a heavy weight component, when

it is running on the Java platform for Unix platform, it maps to a real Motif button. In

this relationship, the Motif button is called the peer to the java.awt.Button. If you

create two Buttons, two peers and hence two Motif Buttons are also created. The Java

platform communicates with the Motif Buttons using the Java Native Interface. For

each and every component added to the application, there is an additional overhead

tied to the local windowing system, which is why these components are called heavy

weight.

Which package has light weight components?

javax.Swing package. All components in Swing, except JApplet, JDialog, JFrame and

JWindow are lightweight components.

© Copyright : IT Engg Portal – www.itportal.in 64

What are peerless components?

The peerless components are called light weight components.

What is the difference between the Font and FontMetrics classes?

The FontMetrics class is used to define implementation-specific properties, such as

ascent and descent, of a Font object

What is the difference between the Reader/Writer class hierarchy and the

InputStream/OutputStream class hierarchy?

The Reader/Writer class hierarchy is character-oriented, and the

InputStream/OutputStream class hierarchy is byte-oriented.

What classes of exceptions may be caught by a catch clause? A catch clause can catch any exception that may be assigned to the Throwable

type. This includes the Error and Exception types.

What is the difference between throw and throws keywords? The throw keyword denotes a statement that causes an exception to be initiated. It

takes the Exception object to be thrown as argument. The exception will be

caught by an immediately encompassing try-catch construction or propagated

further up the calling hierarchy.

The throws keyword is a modifier of a method that designates that exceptions

may come out of the method, either by virtue of the method throwing the

exception itself or because it fails to catch such exceptions that a method it calls

may throw.

If a class is declared without any access modifiers, where may the class be

accessed? A class that is declared without any access modifiers is said to have package or

friendly access. This means that the class can only be accessed by other classes

and interfaces that are defined within the same package.

What is the Map interface?

The Map interface replaces the JDK 1.1 Dictionary class and is used associate

keys with values.

Does a class inherit the constructors of its super class? A class does not inherit constructors from any of its superclasses.

© Copyright : IT Engg Portal – www.itportal.in 65

Name primitive Java types.

The primitive types are byte, char, short, int, long, float, double, and Boolean.

Which class should you use to obtain design information about an object? The Class class is used to obtain information about an object's design.

How can a GUI component handle its own events? A component can handle its own events by implementing the required event-

listener interface and adding itself as its own event listener.

How are the elements of a GridBagLayout organized?

The elements of a GridBagLayout are organized according to a grid. However,

the elements are of different sizes and may occupy more than one row or column

of the grid. In addition, the rows and columns may have different sizes.

What advantage do Java's layout managers provide over traditional

windowing systems? Java uses layout managers to lay out components in a consistent manner across

all windowing platforms. Since Java's layout managers aren't tied to absolute

sizing and positioning, they are able to accommodate platform-specific

differences among windowing systems.

What are the problems faced by Java programmers who don't use layout

managers?

Without layout managers, Java programmers are faced with determining how

their GUI will be displayed across multiple windowing systems and finding a

common sizing and positioning that will work within the constraints imposed by

each windowing system.

What is the difference between static and non-static variables? A static variable is associated with the class as a whole rather than with specific

instances of a class. Non-static variables take on unique values with each object

instance.

What is the difference between the paint() and repaint() methods? The paint() method supports painting via a Graphics object. The repaint() method

is used to cause paint() to be invoked by the AWT painting thread.

© Copyright : IT Engg Portal – www.itportal.in 66

What is the purpose of the File class? The File class is used to create objects that provide access to the files and

directories of a local file system.

Why would you use a synchronized block vs. synchronized method? Synchronized blocks place locks for shorter periods than synchronized methods.

What restrictions are placed on method overriding?

Overridden methods must have the same name, argument list, and return type. The

overriding method may not limit the access of the method it overrides. The overriding

method may not throw any exceptions that may not be thrown by the overridden

method.

What is casting? There are two types of casting, casting between primitive numeric types and casting

between object references. Casting between numeric types is used to convert larger

values, such as double values, to smaller values, such as byte values. Casting between

object references is used to refer to an object by a compatible class, interface, or array

type reference.

Explain the usage of the keyword transient? This keyword indicates that the value of this member variable does not have to be

serialized with the object. When the class will be de-serialized, this variable will be

initialized with a default value of its data type (i.e. zero for integers).

What class allows you to read objects directly from a stream? The ObjectInputStream class supports the reading of objects from input streams.

How are this() and super() used with constructors? this() is used to invoke a constructor of the same class. super() is used to invoke a

superclass constructor.

How is it possible for two String objects with identical values not to be equal

under the == operator? How are this() and super() used with constructors? The == operator compares two objects to determine if they are the same objects in

memory. It is possible for two String objects to have the same value, but located in

different areas of memory.

© Copyright : IT Engg Portal – www.itportal.in 67

What is an IO filter?

An IO filter is an object that reads from one stream and writes to another, usually

altering the data in some way as it is passed from one stream to another.

What is the Set interface? The Set interface provides methods for accessing the elements of a finite mathematical

set. Sets do not allow duplicate elements.

How can you force garbage collection? You can't force GC, but could request it by calling System.gc(). JVM does not

guarantee that GC will be started immediately.

What is the purpose of the enableEvents() method? The enableEvents() method is used to enable an event for a particular object.

Normally, an event is enabled when a listener is added to an object for a particular

event. The enableEvents() method is used by objects that handle events by overriding

their event-dispatch methods.

What is the difference between the File and RandomAccessFile classes? The File class encapsulates the files and directories of the local file system. The

RandomAccessFile class provides the methods needed to directly access data

contained in any part of a file.

What interface must an object implement before it can be written to a stream as

an object? An object must implement the Serializable or Externalizable interface before it can be

written to a stream as an object.

What is the ResourceBundle class?

The ResourceBundle class is used to store locale-specific resources that can be loaded

by a program to tailor the program's appearance to the particular locale in which it is

being run.

How do you know if an explicit object casting is needed? If you assign a superclass object to a variable of a subclass's data type, you need to do

explicit casting. For example:

Object a; Customer b; b = (Customer) a;

© Copyright : IT Engg Portal – www.itportal.in 68

When you assign a subclass to a variable having a supeclass type, the casting is

performed automatically.

What is a Java package and how is it used? A Java package is a naming context for classes and interfaces. A package is used to

create a separate name space for groups of classes and interfaces. Packages are also

used to organize related classes and interfaces into a single API unit and to control

accessibility to these classes and interfaces.

How do you restrict a user to cut and paste from the html page? Using Servlet or client side scripts to lock keyboard keys. It is one of solutions.

What are the Object and Class classes used for?

The Object class is the highest-level class in the Java class hierarchy. The Class

class is used to represent the classes and interfaces that are loaded by a Java

program.

What is Serialization and deserialization ? Serialization is the process of writing the state of an object to a byte stream.

Deserialization is the process of restoring these objects.

Explain the usage of Java packages. This is a way to organize files when a project consists of multiple modules. It also

helps resolve naming conflicts when different packages have classes with the

same names. Packages access level also allows you to protect data from being

used by the non-authorized classes.

Does the code in finally block get executed if there is an exception and a

return statement in a catch block? If an exception occurs and there is a return statement in catch block, the finally

block is still executed. The finally block will not be executed when the

System.exit(1) statement is executed earlier or the system shut down earlier or the

memory is used up earlier before the thread goes to finally block.

Is Java a super set of JavaScript? No. They are completely different. Some syntax may be similar.

© Copyright : IT Engg Portal – www.itportal.in 69

What is a Container in a GUI?

A Container contains and arranges other components (including other containers)

through the use of layout managers, which use specific layout policies to

determine where components should go as a function of the size of the container.

How the object oriented approach helps us keep complexity of software

development under control?

We can discuss such issue from the following aspects:

Objects allow procedures to be encapsulated with their data to reduce potential

interference.

Inheritance allows well-tested procedures to be reused and enables changes to

make once and have effect in all relevant places.

The well-defined separations of interface and implementation allow constraints to

be imposed on inheriting classes while still allowing the flexibility of overriding

and overloading.

What is polymorphism? Polymorphism means "having many forms". It allows methods (may be variables)

to be written that needn't be concerned about the specifics of the objects they will

be applied to. That is, the method can be specified at a higher level of abstraction

and can be counted on to work even on objects of un-conceived classes.

What is design by contract? The design by contract specifies the obligations of a method to any other methods

that may use its services and also theirs to it. For example, the preconditions

specify what the method required to be true when the method is called. Hence

making sure that preconditions are. Similarly, postconditions specify what must

be true when the method is finished, thus the called method has the responsibility

of satisfying the post conditions.

In Java, the exception handling facilities support the use of design by contract,

especially in the case of checked exceptions. The assert keyword can be used to

make such contracts.

What are use cases?

A use case describes a situation that a program might encounter and what

behavior the program should exhibit in that circumstance. It is part of the analysis

of a program. The collection of use cases should, ideally, anticipate all the

© Copyright : IT Engg Portal – www.itportal.in 70

standard circumstances and many of the extraordinary circumstances possible so

that the program will be robust.

What is scalability and performance?

Performance is a measure of "how fast can you perform this task." and scalability

describes how an application behaves as its workload and available computing

resources increase.

What is the benefit of subclass? Generally: The sub class inherits all the public methods and the implementation.

The sub class inherits all the protected methods and their implementation.

The sub class inherits all the default(non-access modifier) methods and their

implementation.

The sub class also inherits all the public, protected and default member variables

from the super class.

The constructors are not part of this inheritance model.

How to add menushortcut to menu item? If you have a button instance called aboutButton, you may add menu short cut by

calling aboutButton.setMnemonic('A'), so the user may be able to use Alt+A to

click the button.

In System.out.println(),what is System,out and println,pls explain?

System is a predefined final class,out is a PrintStream object acting as a field

member and println is a built-in overloaded method in the out object.

Can you write a Java class that could be used both as an applet as well as an

application? A. Yes. Add a main() method to the applet.

Can you make an instance of an abstract class? For example -

java.util.Calender is an abstract class with a method getInstance() which

returns an instance of the Calender class. No! You cannot make an instance of an abstract class. An abstract class has to be

sub-classed. If you have an abstract class and you want to use a method which has

been implemented, you may need to subclass that abstract class, instantiate your

subclass and then call that method.

© Copyright : IT Engg Portal – www.itportal.in 71

What is the output of x > y? a:b = p*q when x=1,y=2,p=3,q=4? When this kind of question has been asked, find the problems you think is

necessary to ask back before you give an answer. Ask if variables a and b have

been declared or initialized. If the answer is yes. You can say that the syntax is

wrong. If the statement is rewritten as: x

What is the difference between Swing and AWT components? AWT components are heavy-weight, whereas Swing components are lightweight.

Heavy weight components depend on the local windowing toolkit. For example,

java.awt.Button is a heavy weight component, when it is running on the Java

platform for Unix platform, it maps to a real Motif button.

Why Java does not support pointers? Because pointers are unsafe. Java uses reference types to hide pointers and

programmers feel easier to deal with reference types without pointers. This is

why Java and C-sharp shine.

Parsers? DOM vs SAX parser

Parsers are fundamental xml components, a bridge between XML documents and

applications that process that XML. The parser is responsible for handling xml

syntax, checking the contents of the document against constraints established in a

DTD or Schema.

DOM

1. Tree of nodes

2. Memory: Occupies more memory, preffered for small XML documents

3. Slower at runtime

4. Stored as objects

5. Programmatically easy

6. Ease of navigation

SAX

1. Sequence of events

2. Doesn't use any memory preferred for large documents

3. Faster at runtime

4. Objects are to be created

5. Need to write code for creating objects

6. Backward navigation is not possible as it sequentially processes the document

© Copyright : IT Engg Portal – www.itportal.in 72

Can you declare a class as private? Yes, we can declare a private class as an inner class. For example,

class MyPrivate {

private static class MyKey {

String key = "12345";

}

public static void main(String[] args) {

System.out.println(new MyKey().key);//prints 12345

}

}

What is the difference between shallow copy and deep copy?

Shallow copy shares the same reference with the original object like cloning,

whereas the deep copy get a duplicate instance of the original object. If the

shallow copy has been changed, the original object will be reflected and vice

versa.

Can one create a method which gets a String and modifies it? No. In Java, Strings are constant or immutable; their values cannot be changed

after they are created, but they can be shared. Once you change a string, you

actually create a new object. For example:

String s = "abc"; //create a new String object representing "abc"

s = s.toUpperCase(); //create another object representing "ABC"

Why is multiple inheritance not possible in Java? It depends on how you understand "inheritance". Java can only "extends" one

super class, but can "implements" many interfaces; that doesn't mean the multiple

inheritance is not possible. You may use interfaces to make inheritance work for

you. Or you may need to work around. For example, if you cannot get a feature

from a class because your class has a super class already, you may get that class's

feature by declaring it as a member field or getting an instance of that class. So

the answer is that multiple inheritance in Java is possible.

What's the difference between constructors and other methods? Constructors must have the same name as the class and can not return a value.

They are only called once while regular methods could be called many times.

© Copyright : IT Engg Portal – www.itportal.in 73

What is the relationship between synchronized and volatile keyword?

The JVM is guaranteed to treat reads and writes of data of 32 bits or less as

atomic.(Some JVM might treat reads and writes of data of 64 bits or less as atomic in

future) For long or double variable, programmers should take care in multi-threading

environment. Either put these variables in a synchronized method or block, or declare

them volatile.

This class (IncrementImpl) will be used by various threads concurrently; can you

see the inherent flaw(s)? How would you improve it?

public class IncrementImpl {

private static int counter = 0;

public synchronized void increment() {

counter++;

}

public int getCounter() {

return counter;

}

}

The counter is static variable which is shared by multiple instances of this class. The

increment() method is synchronized, but the getCounter() should be synchronized too.

Otherwise the Java run-time system will not guarantee the data integrity and the race

conditions will occur. The famous producer/consumer example listed at Sun's thread

tutorial site will tell more.

one of solutions

public class IncrementImpl {

private static int counter = 0;

public synchronized void increment() {

counter++;

}

public synchronized int getCounter() {

return counter;

}

}

What are the drawbacks of inheritance?

Since inheritance inherits everything from the super class and interface, it may make

© Copyright : IT Engg Portal – www.itportal.in 74

the subclass too clustering and sometimes error-prone when dynamic overriding or

dynamic overloading in some situation. In addition, the inheritance may make peers

hardly understand your code if they don't know how your super-class acts and add

learning curve to the process of development.

Usually, when you want to use a functionality of a class, you may use subclass to

inherit such function or use an instance of this class in your class. Which is better,

depends on your specification.

Is there any other way that you can achieve inheritance in Java? There are a couple of ways. As you know, the straight way is to "extends" and/or

"implements". The other way is to get an instance of the class to achieve the

inheritance. That means to make the supposed-super-class be a field member. When

you use an instance of the class, actually you get every function available from this

class, but you may lose the dynamic features of OOP

Two methods have key words static synchronized and synchronized separately.

What is the difference between them? Both are synchronized methods. One is instance method, the other is class method.

Method with static modifier is a class method. That means the method belongs to class

itself and can be accessed directly with class name and is also called Singleton design.

The method without static modifier is an instance method. That means the instance

method belongs to its object. Every instance of the class gets its own copy of its

instance method.

When synchronized is used with a static method, a lock for the entire class is obtained.

When synchronized is used with a non-static method, a lock for the particular object

(that means instance) of the class is obtained.

Since both methods are synchronized methods, you are not asked to explain what is a

synchronized method. You are asked to tell the difference between instance and class

method. Of course, your explanation to how synchronized keyword works doesn't

hurt. And you may use this opportunity to show your knowledge scope.

How do you create a read-only collection?

The Collections class has six methods to help out here:

1. unmodifiableCollection(Collection c)

2. unmodifiableList(List list)

3. unmodifiableMap(Map m)

4. unmodifiableSet(Set s)

© Copyright : IT Engg Portal – www.itportal.in 75

5. unmodifiableSortedMap(SortedMap m)

6. unmodifiableSortedSet(SortedSet s)

If you get an Iterator from one of these unmodifiable collections, when you call

remove(), it will throw an UnsupportedOperationException.

Can a private method of a superclass be declared within a subclass? Sure. A private field or method or inner class belongs to its declared class and hides

from its subclasses. There is no way for private stuff to have a runtime overloading or

overriding (polymorphism) features.

Why Java does not support multiple inheritance ? This is a classic question. Yes or No depends on how you look at Java. If you focus on

the syntax of "extends" and compare with C++, you may answer 'No' and give

explanation to support you. Or you may answer 'Yes'. Recommend you to say 'Yes'.

Java DOES support multiple inheritance via interface implementation. Some people

may not think in this way. Give explanation to support your point.

What is the difference between final, finally and finalize?

Short answer:

final - declares constant

finally - relates with exception handling

finalize - helps in garbage collection

If asked to give details, explain:

final field, final method, final class

try/finally, try/catch/finally

protected void finalize() in Object class

What kind of security tools are available in J2SE 5.0? There are three tools that can be used to protect application working within the

scope of security policies set at remote sites.

keytool -- used to manage keystores and certificates.

jarsigner -- used to generate and verify JAR signatures.

policytool -- used for managing policy files.

There are three tools that help obtain, list and manage Kerberos tickets.

kinit -- used to obtain Kerberos V5 tickets.

tklist -- used to list entries in credential cache and key tab.

ktab -- used to help manage entries in the key table.

© Copyright : IT Engg Portal – www.itportal.in 76

How to make an array copy from System? There is a method called arraycopy in the System class. You can do it:

System.arraycopy(sourceArray, srcOffset, destinationArray, destOffset,

numOfElements2Copy);

When you use this method, the destinationArray will be filled with the elements

of sourceArray at the length specified.

Can we use System.arraycopy() method to copy the same array? Yes, you can. The source and destination arrays can be the same if you want to

copy a subset of the array to another area within that array.

What is shallow copy or shallow clone in array cloning? Cloning an array invloves creating a new array of the same size and type and

copying all the old elements into the new array. But such copy is called shallow

copy or shallow clone because any changes to the object would be reflected in

both arrays.

When is the ArrayStoreException thrown? When copying elements between different arrays, if the source or destination

arguments are not arrays or their types are not compatible, an

ArrayStoreException will be thrown.

How to check two arrays to see if contents have the same types and contain

the same elements? One of options is to use the equals() method of Arrays class.

Arrays.equals(a, b);

If the array types are different, a compile-time error will happen.

Can you call one constructor from another if a class has multiple

constructors? Yes. Use this() syntax.

What are the different types of inner classes? There are four different types of inner classes in Java. They are: a)Static member

classes , a static member class has access to all static methods of the parent, or

top-level, class b) Member classes, the member class is instance specific and has

© Copyright : IT Engg Portal – www.itportal.in 77

access to any and all methods and members, even the parent's this reference c)

Local classes, are declared within a block of code and are visible only within that

block, just as any other method variable. d) Anonymous classes, is a local class

that has no name

In which case would you choose a static inner class?

Interesting one, static inner classes can access the outer class's protected and

private fields. This is both a positive and a negative point for us since we can, in

essence, violate the encapsulation of the outer class by mucking up the outer

class's protected and private fields. The only proper use of that capability is to

write white-box tests of the class -- since we can induce cases that might be very

hard to induce via normal black-box tests (which don't have access to the internal

state of the object). Second advantage,if I can say, is that, we can this static

concept to impose restriction on the inner class. Again as discussed in earlier

point, an Inner class has access to all the public, private and protected members of

the parent class. Suppose you want to restrict the access even to inner class, how

would you go ahead? Making the inner class static enforces it to access only the

public static members of the outer class( Since, protected and private members

are not supposed to be static and that static members can access only other static

members). If it has to access any non-static member, it has to create an instance

of the outer class which leads to accessing only public members.

What is weak reference in Java A weak reference is one that does not prevent the referenced object from being

garbage collected. You might use them to manage a HashMap to look up a cache

of objects. A weak reference is a reference that does not keep the object it refers

to alive. A weak reference is not counted as a reference in garbage collection. If

the object is not referred to elsewhere as well, it will be garbage collected.

What is the difference between final, finally and finalize?

final is used for making a class no-subclassable, and making a member variable

as a constant which cannot be modified. finally is usually used to release all the

resources utilized inside the try block. All the resources present in the finalize

method will be garbage collected whenever GC is called. Though finally and

finalize seem to be for a similar task there is an interesting tweak here, usually I

prefer finally than finalize unless it is unavoidable. This is because the code in

finally block is guaranteed of execution irrespective of occurrence of exception,

© Copyright : IT Engg Portal – www.itportal.in 78

while execution of finalize is not guarenteed.finalize method is called by the

garbage collector on an object when the garbage collector determines that there

are no more references to the object. Presumably the garbage collector will, like

its civil servant namesake, visit the heap on a regular basis to clean up resources

that are no longer in use. Garbage collection exists to prevent programmers from

calling delete. This is a wonderful feature. For example, if you can't call delete,

then you can't accidentally call delete twice on the same object. However,

removing delete from the language is not the same thing as automatically

cleaning up. To add to it, Garbage collection might not ever run. If garbage

collection runs at all, and an object is no longer referenced, then that object's

finalize will run. Also, across multiple objects, finalize order is not predictable.

The correct approach to resource cleanup in Java language programs does not rely

on finalize. Instead, you simply write explicit close methods for objects that wrap

native resources. If you take this approach, you must document that the close

method exists and when it should be called. Callers of the object must then

remember to call close when they are finished with a resource.

What's the difference between the methods sleep() and wait() The code sleep(1000); puts thread aside for exactly one second. The code

wait(1000), causes a wait of up to one second. A thread could stop waiting earlier

if it receives the notify() or notifyAll() call. The method wait() is defined in the

class Object and the method sleep() is defined in the class Thread.

The following statement prints true or false, why? byte[] a = { 1, 2, 3 };,

byte[] b = (byte[]) a.clone();

System.out.println(a == b);

The false will be printed out. Because the two arrays have distinctive memory

addresses. Starting in Java 1.2, we can use java.util.Arrays.equals(a, b) to

compare whether two arrays have the same contents.

Why do we need to use getSystemResource() and getSystemResources()

method to load resources?

Because we want to look for resources strictly from the system classpath, These

methods use the system ClassLoader to locate resources, which gives you stricter

control of the resources used by the application.

© Copyright : IT Engg Portal – www.itportal.in 79

ArithmeticException? The ArithmeticException is thrown when integer is divided by zero or taking the

remainder of a number by zero. It is never thrown in floating-point operations.

What is a transient variable? A transient variable is a variable that may not be serialized.

Which containers use a border Layout as their default layout? The window, Frame and Dialog classes use a border layout as their default layout.

Why do threads block on I/O? Threads block on I/O (that is enters the waiting state) so that other threads may

execute while the I/O Operation is performed.

What is the output from System.out.println("Hello"+null);? Hellonull

What is synchronization and why is it important?

With respect to multithreading, synchronization is the capability to control the

access of multiple threads to shared resources. Without synchronization, it is

possible for one thread to modify a shared object while another thread is in the

process of using or updating that object's value. This often leads to significant

errors.

Can a lock be acquired on a class? Yes, a lock can be acquired on a class. This lock is acquired on the class's Class

object.

What's new with the stop(), suspend() and resume() methods in JDK 1.2? The stop(), suspend() and resume() methods have been deprecated in JDK 1.2.

Is null a keyword? The null value is not a keyword.

What is the preferred size of a component? The preferred size of a component is the minimum component size that will allow

the component to display normally.

© Copyright : IT Engg Portal – www.itportal.in 80

What method is used to specify a container's layout?

The setLayout() method is used to specify a container's layout.

Which containers use a FlowLayout as their default layout? The Panel and Applet classes use the FlowLayout as their default layout.

What state does a thread enter when it terminates its processing? When a thread terminates its processing, it enters the dead state.

What is the Collections API? The Collections API is a set of classes and interfaces that support operations on

collections of objects.

Which characters may be used as the second character of an identifier, but not as

the first character of an identifier? The digits 0 through 9 may not be used as the first character of an identifier but they

may be used after the first character of an identifier.

What is the List interface? The List interface provides support for ordered collections of objects.

How does Java handle integer overflows and underflows? It uses those low order bytes of the result that can fit into the size of the type allowed

by the operation.

What is the Vector class? The Vector class provides the capability to implement a growable array of objects

What modifiers may be used with an inner class that is a member of an outer

class?

A (non-local) inner class may be declared as public, protected, private, static, final, or

abstract.

What is an Iterator interface? The Iterator interface is used to step through the elements of a Collection.

What is the difference between the >> and >>> operators? The >> operator carries the sign bit when shifting right. The >>> zero-fills bits that

have been shifted out.

© Copyright : IT Engg Portal – www.itportal.in 81

Which method of the Component class is used to set the position and size of a

component? setBounds()

How many bits are used to represent Unicode, ASCII, UTF-16, and UTF-8

characters?

Unicode requires 16 bits and ASCII require 7 bits. Although the ASCII character set

uses only 7 bits, it is usually represented as 8 bits. UTF-8 represents characters using

8, 16, and 18 bit patterns. UTF-16 uses 16-bit and larger bit patterns.

What is the difference between yielding and sleeping? When a task invokes its yield() method, it returns to the ready state. When a task

invokes its sleep() method, it returns to the waiting state.

Which java.util classes and interfaces support event handling? The EventObject class and the EventListener interface support event processing.

Is sizeof a keyword?

The sizeof operator is not a keyword.

What are wrapper classes? Wrapper classes are classes that allow primitive types to be accessed as objects.

Does garbage collection guarantee that a program will not run out of memory? Garbage collection does not guarantee that a program will not run out of memory. It is

possible for programs to use up memory resources faster than they are garbage

collected. It is also possible for programs to create objects that are not subject to

garbage collection.

What restrictions are placed on the location of a package statement within a

source code file? A package statement must appear as the first line in a source code file (excluding

blank lines and comments).

Can an object's finalize() method be invoked while it is reachable?

An object's finalize() method cannot be invoked by the garbage collector while the

object is still reachable. However, an object's finalize() method may be invoked by

other objects.

© Copyright : IT Engg Portal – www.itportal.in 82

What is the immediate superclass of the Applet class? Panel

What is the difference between preemptive scheduling and time slicing? Under preemptive scheduling, the highest priority task executes until it enters the

waiting or dead states or a higher priority task comes into existence. Under time

slicing, a task executes for a predefined slice of time and then reenters the pool of

ready tasks. The scheduler then determines which task should execute next, based on

priority and other factors.

Name three Component subclasses that support painting. The Canvas, Frame, Panel, and Applet classes support painting.

What value does readLine() return when it has reached the end of a file? The readLine() method returns null when it has reached the end of a file.

What is the immediate superclass of the Dialog class? Window.

What is clipping? Clipping is the process of confining paint operations to a limited area or shape.

What is a native method? A native method is a method that is implemented in a language other than Java.

Can a for statement loop indefinitely?

Yes, a for statement can loop indefinitely. For example, consider the following: for(;;)

;

What are order of precedence and associativity, and how are they used? Order of precedence determines the order in which operators are evaluated in

expressions. Associatity determines whether an expression is evaluated left-to-right or

right-to-left

When a thread blocks on I/O, what state does it enter? A thread enters the waiting state when it blocks on I/O.

To what value is a variable of the String type automatically initialized? The default value of a String type is null.

© Copyright : IT Engg Portal – www.itportal.in 83

What is the catch or declare rule for method declarations? If a checked exception may be thrown within the body of a method, the method must

either catch the exception or declare it in its throws clause.

What is the difference between a MenuItem and a CheckboxMenuItem? The CheckboxMenuItem class extends the MenuItem class to support a menu item that

may be checked or unchecked.

What is a task's priority and how is it used in scheduling?

A task's priority is an integer value that identifies the relative order in which it should

be executed with respect to other tasks. The scheduler attempts to schedule higher

priority tasks before lower priority tasks.

What class is the top of the AWT event hierarchy? The java.awt.AWTEvent class is the highest-level class in the AWT event-class

hierarchy.

When a thread is created and started, what is its initial state? A thread is in the ready state after it has been created and started.

Can an anonymous class be declared as implementing an interface and extending

a class? An anonymous class may implement an interface or extend a superclass, but may not

be declared to do both.

What is the range of the short type?

The range of the short type is -(2^15) to 2^15 - 1.

What is the range of the char type? The range of the char type is 0 to 2^16 - 1.

In which package are most of the AWT events that support the event-delegation

model defined? Most of the AWT-related events of the event-delegation model are defined in the

java.awt.event package. The AWTEvent class is defined in the java.awt package.

What is the immediate super class of Menu? What is the immediate super class of Menu? MenuItem

© Copyright : IT Engg Portal – www.itportal.in 84

What is the purpose of finalization? The purpose of finalization is to give an unreachable object the opportunity to perform

any cleanup processing before the object is garbage collected.

Which class is the immediate super class of the MenuComponent class. Object

What invokes a thread's run() method? After a thread is started, via its start() method or that of the Thread class, the JVM

invokes the thread's run() method when the thread is initially executed.

What is the difference between the Boolean & operator and the && operator?

If an expression involving the Boolean & operator is evaluated, both operands are

evaluated. Then the & operator is applied to the operand. When an expression

involving the && operator is evaluated, the first operand is evaluated. If the first

operand returns a value of true then the second operand is evaluated. The && operator

is then applied to the first and second operands. If the first operand evaluates to false,

the evaluation of the second operand is skipped.

Name three subclasses of the Component class.

Box.Filler, Button, Canvas, Checkbox, Choice, Container, Label, List, Scrollbar, or

TextComponent

What is the GregorianCalendar class? The GregorianCalendar provides support for traditional Western calendars.

Which Container method is used to cause a container to be laid out and

redisplayed? validate()

What is the purpose of the Runtime class? The purpose of the Runtime class is to provide access to the Java runtime system.

How many times may an object's finalize() method be invoked by the garbage

collector? An object's finalize() method may only be invoked once by the garbage collector.

What is the purpose of the finally clause of a try-catch-finally statement? garbage

collector?

© Copyright : IT Engg Portal – www.itportal.in 85

The finally clause is used to provide the capability to execute code no matter whether

or not an exception is thrown or caught.

What is the argument type of a program's main() method? A program's main() method takes an argument of the String[] type.

Which Java operator is right associative? The = operator is right associative.

What is the Locale class? The Locale class is used to tailor program output to the conventions of a particular

geographic, political, or cultural region.

Can a double value be cast to a byte? Yes, a double value can be cast to a byte.

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

A break statement results in the termination of the statement to which it applies

(switch, for, do, or while). A continue statement is used to end the current loop

iteration and return control to the loop statement.

What must a class do to implement an interface? It must provide all of the methods in the interface and identify the interface in its

implements clause.

What method is invoked to cause an object to begin executing as a separate

thread? The start() method of the Thread class is invoked to cause an object to begin executing

as a separate thread.

Name two subclasses of the TextComponent class. TextField and TextArea

What is the advantage of the event-delegation model over the earlier event-

inheritance model? The event-delegation model has two advantages over the event-inheritance model.

First, it enables event handling to be handled by objects other than the ones that

generate the events (or their containers). This allows a clean separation between a

component's design and its use. The other advantage of the event-delegation model is

© Copyright : IT Engg Portal – www.itportal.in 86

that it performs much better in applications where many events are generated. This

performance improvement is due to the fact that the event-delegation model does not

have to repeatedly process unhandled events, as is the case of the event-inheritance

model.

Which containers may have a MenuBar?

Frame

How are commas used in the initialization and iteration parts of a for statement? Commas are used to separate multiple statements within the initialization and iteration

parts of a for statement.

What is the purpose of the wait(), notify(), and notifyAll() methods? The wait(),notify(), and notifyAll() methods are used to provide an efficient way for

threads to wait for a shared resource. When a thread executes an object's wait()

method, it enters the waiting state. It only enters the ready state after another thread

invokes the object's notify() or notifyAll() methods.

What is an abstract method? An abstract method is a method whose implementation is deferred to a subclass.

How are Java source code files named? A Java source code file takes the name of a public class or interface that is defined

within the file. A source code file may contain at most one public class or interface. If

a public class or interface is defined within a source code file, then the source code file

must take the name of the public class or interface. If no public class or interface is

defined within a source code file, then the file must take on a name that is different

than its classes and interfaces. Source code files use the .java extension.

What is the relationship between the Canvas class and the Graphics class? A Canvas object provides access to a Graphics object via its paint() method.

What are the high-level thread states? The high-level thread states are ready, running, waiting, and dead.

What value does read() return when it has reached the end of a file?

The read() method returns -1 when it has reached the end of a file.

© Copyright : IT Engg Portal – www.itportal.in 87

Can a Byte object be cast to a double value? No, an object cannot be cast to a primitive value.

What is the difference between a static and a non-static inner class? A non-static inner class may have object instances that are associated with instances of

the class's outer class. A static inner class does not have any object instances.

What is the difference between the String and StringBuffer classes? String objects are constants. StringBuffer objects are not.

If a variable is declared as private, where may the variable be accessed? A private variable may only be accessed within the class in which it is declared.

What is an object's lock and which objects have locks?

An object's lock is a mechanism that is used by multiple threads to obtain

synchronized access to the object. A thread may execute a synchronized method

of an object only after it has acquired the object's lock. All objects and classes

have locks. A class's lock is acquired on the class's Class object.

What is the Dictionary class? The Dictionary class provides the capability to store key-value pairs.

How are the elements of a BorderLayout organized? The elements of a BorderLayout are organized at the borders (North, South, East,

and West) and the center of a container.

What is the % operator? It is referred to as the modulo or remainder operator. It returns the remainder of

dividing the first operand by the second operand.

When can an object reference be cast to an interface reference? An object reference be cast to an interface reference when the object implements

the referenced interface.

What is the difference between a Window and a Frame? The Frame class extends Window to define a main application window that can

have a menu bar.

© Copyright : IT Engg Portal – www.itportal.in 88

Which class is extended by all other classes? The Object class is extended by all other classes.

Can an object be garbage collected while it is still reachable?

A reachable object cannot be garbage collected. Only unreachable objects may be

garbage collected..

Is the ternary operator written x : y ? z or x ? y : z ? It is written x ? y : z.

What is the difference between the Font and FontMetrics classes? The FontMetrics class is used to define implementation-specific properties, such

as ascent and descent, of a Font object.

How is rounding performed under integer division? The fractional part of the result is truncated. This is known as rounding toward

zero.

What happens when a thread cannot acquire a lock on an object? If a thread attempts to execute a synchronized method or synchronized statement

and is unable to acquire an object's lock, it enters the waiting state until the lock

becomes available.

What is the difference between the Reader/Writer class hierarchy and the

InputStream/OutputStream class hierarchy? The Reader/Writer class hierarchy is character-oriented, and the

InputStream/OutputStream class hierarchy is byte-oriented.

What classes of exceptions may be caught by a catch clause?

A catch clause can catch any exception that may be assigned to the Throwable

type. This includes the Error and Exception types.

If a class is declared without any access modifiers, where may the class be

accessed? A class that is declared without any access modifiers is said to have package

© Copyright : IT Engg Portal – www.itportal.in 89

access. This means that the class can only be accessed by other classes and

interfaces that are defined within the same package.

What is the SimpleTimeZone class?

The SimpleTimeZone class provides support for a Gregorian calendar.

What is the Map interface?

The Map interface replaces the JDK 1.1 Dictionary class and is used associate

keys with values.

Does a class inherit the constructors of its superclass? A class does not inherit constructors from any of its super classes.

For which statements does it make sense to use a label?

The only statements for which it makes sense to use a label are those statements

that can enclose a break or continue statement.

What is the purpose of the System class? The purpose of the System class is to provide access to system resources.

Which TextComponent method is used to set a TextComponent to the read-

only state? setEditable()

How are the elements of a CardLayout organized? The elements of a CardLayout are stacked, one on top of the other, like a deck of

cards.

Is &&= a valid Java operator? No, it is not.

Name the eight primitive Java types. The eight primitive types are byte, char, short, int, long, float, double, and

boolean.

Which class should you use to obtain design information about an object? The Class class is used to obtain information about an object's design.

© Copyright : IT Engg Portal – www.itportal.in 90

What is the relationship between clipping and repainting? When a window is repainted by the AWT painting thread, it sets the clipping

regions to the area of the window that requires repainting.

Is "abc" a primitive value?

The String literal "abc" is not a primitive value. It is a String object.

What is the relationship between an event-listener interface and an event-

adapter class? An event-listener interface defines the methods that must be implemented by an

event handler for a particular kind of event. An event adapter provides a default

implementation of an event-listener interface.

What restrictions are placed on the values of each case of a switch

statement? During compilation, the values of each case of a switch statement must evaluate

to a value that can be promoted to an int value.

What modifiers may be used with an interface declaration? An interface may be declared as public or abstract.

Is a class a subclass of itself? A class is a subclass of itself.

What is the highest-level event class of the event-delegation model?

The java.util.EventObject class is the highest-level class in the event-delegation

class hierarchy.

What event results from the clicking of a button? The ActionEvent event is generated as the result of the clicking of a button.

How can a GUI component handle its own events? A component can handle its own events by implementing the required event-

listener interface and adding itself as its own event listener.

What is the difference between a while statement and a do statement? A while statement checks at the beginning of a loop to see whether the next loop

iteration should occur. A do statement checks at the end of a loop to see whether

© Copyright : IT Engg Portal – www.itportal.in 91

the next iteration of a loop should occur. The do statement will always execute

the body of a loop at least once.

How are the elements of a GridBagLayout organized? The elements of a GridBagLayout are organized according to a grid. However,

the elements are of different sizes and may occupy more than one row or column

of the grid. In addition, the rows and columns may have different sizes.

What advantage do Java's layout managers provide over traditional

windowing systems?

Java uses layout managers to lay out components in a consistent manner across

all windowing platforms. Since Java's layout managers aren't tied to absolute

sizing and positioning, they are able to accommodate platform-specific

differences among windowing systems.

What is the Collection interface? The Collection interface provides support for the implementation of a

mathematical bag - an unordered collection of objects that may contain

duplicates.

What modifiers can be used with a local inner class? A local inner class may be final or abstract.

What is the difference between static and non-static variables? A static variable is associated with the class as a whole rather than with specific

instances of a class. Non-static variables take on unique values with each object

instance.

What is the difference between the paint() and repaint() methods? The paint() method supports painting via a Graphics object. The repaint() method

is used to cause paint() to be invoked by the AWT painting thread.

What is the purpose of the File class? The File class is used to create objects that provide access to the files and

directories of a local file system.

© Copyright : IT Engg Portal – www.itportal.in 92

Can an exception be rethrown?

Yes, an exception can be rethrown.

Which Math method is used to calculate the absolute value of a number? The abs() method is used to calculate absolute values.

How does multithreading take place on a computer with a single CPU?

The operating system's task scheduler allocates execution time to multiple tasks.

By quickly switching between executing tasks, it creates the impression that tasks

execute sequentially.

When does the compiler supply a default constructor for a class? The compiler supplies a default constructor for a class if no other constructors are

provided.

When is the finally clause of a try-catch-finally statement executed? The finally clause of the try-catch-finally statement is always executed unless the

thread of execution terminates or an exception occurs within the execution of the

finally clause.

Which class is the immediate superclass of the Container class? Component

If a method is declared as protected, where may the method be accessed? A protected method may only be accessed by classes or interfaces of the same

package or by subclasses of the class in which it is declared.

How can the Checkbox class be used to create a radio button?

By associating Checkbox objects with a CheckboxGroup.

Which non-Unicode letter characters may be used as the first character of an

identifier? The non-Unicode letter characters $ and _ may appear as the first character of an

identifier

What restrictions are placed on method overloading? Two methods may not have the same name and argument list but different return

types.

© Copyright : IT Engg Portal – www.itportal.in 93

What happens when you invoke a thread's interrupt method while it is

sleeping or waiting? When a task's interrupt() method is executed, the task enters the ready state. The

next time the task enters the running state, an InterruptedException is thrown.

What is the return type of a program's main() method? A program's main() method has a void return type.

Name four Container classes.

Window, Frame, Dialog, FileDialog, Panel, Applet, or ScrollPane

What is the difference between a Choice and a List? A Choice is displayed in a compact form that requires you to pull it down to see

the list of available choices. Only one item may be selected from a Choice. A List

may be displayed in such a way that several List items are visible. A List supports

the selection of one or more List items.

What class of exceptions are generated by the Java run-time system? The Java runtime system generates RuntimeException and Error exceptions.

What class allows you to read objects directly from a stream?

The ObjectInputStream class supports the reading of objects from input streams.

What is the difference between a field variable and a local variable? A field variable is a variable that is declared as a member of a class. A local

variable is a variable that is declared local to a method.

Under what conditions is an object's finalize() method invoked by the

garbage collector? The garbage collector invokes an object's finalize() method when it detects that

the object has become unreachable.

How are this () and super () used with constructors? this() is used to invoke a constructor of the same class. super() is used to invoke a

superclass constructor.

What is the relationship between a method's throws clause and the

exceptions that can be thrown during the method's execution?

© Copyright : IT Engg Portal – www.itportal.in 94

A method's throws clause must declare any checked exceptions that are not

caught within the body of the method.

What is the difference between the JDK 1.02 event model and the event-

delegation model introduced with JDK 1.1? The JDK 1.02 event model uses an event inheritance or bubbling approach. In

this model, components are required to handle their own events. If they do not

handle a particular event, the event is inherited by (or bubbled up to) the

component's container. The container then either handles the event or it is

bubbled up to its container and so on, until the highest-level container has been

tried. In the event-delegation model, specific objects are designated as event

handlers for GUI components. These objects implement event-listener interfaces.

The event-delegation model is more efficient than the event-inheritance model

because it eliminates the processing required to support the bubbling of

unhandled events.

How is it possible for two String objects with identical values not to be equal

under the == operator? The == operator compares two objects to determine if they are the same object in

memory. It is possible for two String objects to have the same value, but located

indifferent areas of memory.

Why are the methods of the Math class static? So they can be invoked as if they are a mathematical code library.

What Checkbox method allows you to tell if a Checkbox is checked? getState()

What state is a thread in when it is executing?

An executing thread is in the running state.

What are the legal operands of the instanceof operator? The left operand is an object reference or null value and the right operand is a

class, interface, or array type.

How are the elements of a GridLayout organized? The elements of a GridBad layout are of equal size and are laid out using the

squares of a grid.

© Copyright : IT Engg Portal – www.itportal.in 95

What an I/O filter? An I/O filter is an object that reads from one stream and writes to another, usually

altering the data in some way as it is passed from one stream to another.

If an object is garbage collected, can it become reachable again? Once an object is garbage collected, it ceases to exist. It can no longer become

reachable again.

What are E and PI?

E is the base of the natural logarithm and PI is mathematical value pi.

Are true and false keywords? The values true and false are not keywords.

What is a void return type? A void return type indicates that a method does not return a value.

What is the purpose of the enableEvents() method?

The enableEvents() method is used to enable an event for a particular object.

Normally, an event is enabled when a listener is added to an object for a

particular event. The enableEvents() method is used by objects that handle events

by overriding their event-dispatch methods.

What is the difference between the File and RandomAccessFile classes? The File class encapsulates the files and directories of the local file system. The

RandomAccessFile class provides the methods needed to directly access data

contained in any part of a file.

What happens when you add a double value to a String? The result is a String object.

What is your platform's default character encoding? If you are running Java on English Windows platforms, it is probably Cp1252. If

you are running Java on English Solaris platforms, it is most likely 8859_1..

Which package is always imported by default?

The java.lang package is always imported by default.

© Copyright : IT Engg Portal – www.itportal.in 96

What interface must an object implement before it can be written to a

stream as an object? An object must implement the Serializable or Externalizable interface before it

can be written to a stream as an object.

How are this and super used? this is used to refer to the current object instance. super is used to refer to the

variables and methods of the superclass of the current object instance.

What is the purpose of garbage collection? The purpose of garbage collection is to identify and discard objects that are no

longer needed by a program so that their resources may be reclaimed and reused.

What is a compilation unit? A compilation unit is a Java source code file.

What interface is extended by AWT event listeners? All AWT event listeners extend the java.util.EventListener interface.

What restrictions are placed on method overriding?

Overridden methods must have the same name, argument list, and return type.

The overriding method may not limit the access of the method it overrides. The

overriding method may not throw any exceptions that may not be thrown by the

overridden method.

How can a dead thread be restarted? A dead thread cannot be restarted.

What happens if an exception is not caught? An uncaught exception results in the uncaughtException() method of the thread's

ThreadGroup being invoked, which eventually results in the termination of the

program in which it is thrown.

What is a layout manager? A layout manager is an object that is used to organize components in a container.

Which arithmetic operations can result in the throwing of an

ArithmeticException? Integer / and % can result in the throwing of an ArithmeticException.

© Copyright : IT Engg Portal – www.itportal.in 97

What are three ways in which a thread can enter the waiting state?

A thread can enter the waiting state by invoking its sleep() method, by blocking

on I/O, by unsuccessfully attempting to acquire an object's lock, or by invoking

an object's wait() method. It can also enter the waiting state by invoking its

(deprecated) suspend() method.

Can an abstract class be final? An abstract class may not be declared as final.

What is the ResourceBundle class? The ResourceBundle class is used to store locale-specific resources that can be

loaded by a program to tailor the program's appearance to the particular locale in

which it is being run.

What happens if a try-catch-finally statement does not have a catch clause to

handle an exception that is thrown within the body of the try statement? The exception propagates up to the next higher level try-catch statement (if any)

or results in the program's termination.

What is numeric promotion? Numeric promotion is the conversion of a smaller numeric type to a larger

numeric type, so that integer and floating-point operations may take place. In

numerical promotion, byte, char, and short values are converted to int values. The

int values are also converted to long values, if necessary. The long and float

values are converted to double values, as required.

What is the difference between a Scrollbar and a ScrollPane? A Scrollbar is a Component, but not a Container. A ScrollPane is a Container. A

ScrollPane handles its own events and performs its own scrolling.

What is the difference between a public and a non-public class?

A public class may be accessed outside of its package. A non-public class may

not be accessed outside of its package.

To what value is a variable of the boolean type automatically initialized? The default value of the boolean type is false.

© Copyright : IT Engg Portal – www.itportal.in 98

Can try statements be nested? Try statements may be tested.

What is the difference between the prefix and postfix forms of the ++

operator? The prefix form performs the increment operation and returns the value of the

increment operation. The postfix form returns the current value all of the

expression and then performs the increment operation on that value.

What is the purpose of a statement block? A statement block is used to organize a sequence of statements as a single

statement group.

What is a Java package and how is it used? A Java package is a naming context for classes and interfaces. A package is used

to create a separate name space for groups of classes and interfaces. Packages are

also used to organize related classes and interfaces into a single API unit and to

control accessibility to these classes and interfaces.

What modifiers may be used with a top-level class?

A top-level class may be public, abstract, or final.

What are the Object and Class classes used for? The Object class is the highest-level class in the Java class hierarchy. The Class

class is used to represent the classes and interfaces that are loaded by a Java

program.

How does a try statement determine which catch clause should be used to

handle an exception? When an exception is thrown within the body of a try statement, the catch clauses

of the try statement are examined in the order in which they appear. The first

catch clause that is capable of handling the exception is executed. The remaining

catch clauses are ignored.

Can an unreachable object become reachable again? An unreachable object may become reachable again. This can happen when the

object's finalize() method is invoked and the object performs an operation which

causes it to become accessible to reachable objects.

© Copyright : IT Engg Portal – www.itportal.in 99

When is an object subject to garbage collection?

An object is subject to garbage collection when it becomes unreachable to the

program in which it is used.

What method must be implemented by all threads? All tasks must implement the run() method, whether they are a subclass of Thread

or implement the Runnable interface.

What methods are used to get and set the text label displayed by a Button

object? getLabel() and setLabel()

Which Component subclass is used for drawing and painting? Canvas

What are the two basic ways in which classes that can be run as threads may

be defined? A thread class may be declared as a subclass of Thread, or it may implement the

Runnable interface.

What are the problems faced by Java programmers who don't use layout

managers? Without layout managers, Java programmers are faced with determining how

their GUI will be displayed across multiple windowing systems and finding a

common sizing and positioning that will work within the constraints imposed by

each windowing system.

What is the difference between an if statement and a switch statement?

The if statement is used to select among two alternatives. It uses a Boolean

expression to decide which alternative should be executed. The switch statement

is used to select among multiple alternatives. It uses an int expression to

determine which alternative should be executed.

Can there be an abstract class with no abstract methods in it? yes.

© Copyright : IT Engg Portal – www.itportal.in 100

Can an Interface be final? yes.

Can an Interface have an inner class? Yes public interface abc { static int i=0; void dd(); class a1 { a1() { int j;

System.out.println("in interfia"); }; public static void main(String a1[]) {

System.out.println("in interfia"); } } }

Can we define private and protected modifiers for variables in interfaces? Yes.

What is Externalizable? Externalizable is an Interface that extends Serializable Interface. And sends data

into Streams in Compressed Format. It has two methods,

writeExternal(ObjectOuput out) and readExternal(ObjectInput in)

What modifiers are allowed for methods in an Interface? Only public and abstract modifiers are allowed for methods in interfaces.

What is a local, member and a class variable?

Variables declared within a method are "local" variables.

Variables declared within the class i.e not within any methods are "member"

variables (global variables).

Variables declared within the class i.e not within any methods and are defined as

"static" are class variables

I made my class Cloneable but I still get 'Can't access protected method

clone. Why? Yeah, some of the Java books, in particular "The Java Programming Language",

imply that all you have to do in order to have your class support clone() is

implement the Cloneable interface. Not so. Perhaps that was the intent at some

point, but that's not the way it works currently. As it stands, you have to

implement your own public clone() method, even if it doesn't do anything special

and just calls super.clone().

What are the different identifier states of a Thread? The different identifiers of a Thread are:

R - Running or runnable thread

© Copyright : IT Engg Portal – www.itportal.in 101

S - Suspended thread

CW - Thread waiting on a condition variable

MW - Thread waiting on a monitor lock

MS - Thread suspended waiting on a monitor lock

What are some alternatives to inheritance?

Delegation is an alternative to inheritance. Delegation means that you include an

instance of another class as an instance variable, and forward messages to the

instance. It is often safer than inheritance because it forces you to think about

each message you forward, because the instance is of a known class, rather than a

new class, and because it doesn't force you to accept all the methods of the super

class: you can provide only the methods that really make sense. On the other

hand, it makes you write more code, and it is harder to re-use (because it is not a

subclass).

Why isn't there operator overloading? Because C++ has proven by example that operator overloading makes code

almost impossible to maintain. In fact there very nearly wasn't even method

overloading in Java, but it was thought that this was too useful for some very

basic methods like print(). Note that some of the classes like DataOutputStream

have unoverloaded methods like writeInt() and writeByte().

What does it mean that a method or field is "static"? Static variables and methods are instantiated only once per class. In other words

they are class variables, not instance variables. If you change the value of a static

variable in a particular object, the value of that variable changes for all instances

of that class.

Static methods can be referenced with the name of the class rather than the name

of a particular object of the class (though that works too). That's how library

methods like System.out.println() work. out is a static field in the

java.lang.System class.

Why do threads block on I/O? Threads block on i/o (that is enters the waiting state) so that other threads may

execute while the i/o Operation is performed.

What is synchronization and why is it important?

With respect to multithreading, synchronization is the capability to control the

© Copyright : IT Engg Portal – www.itportal.in 102

access of multiple threads to shared resources. Without synchronization, it is

possible for one thread to modify a shared object while another thread is in the

process of using or updating that object's value. This often leads to significant

errors.

Is null a keyword? The null value is not a keyword.

Which characters may be used as the second character of an identifier,but

not as the first character of an identifier? The digits 0 through 9 may not be used as the first character of an identifier but

they may be used after the first character of an identifier.

What is the difference between notify() and notifyAll()? notify() is used to unblock one waiting thread; notifyAll() is used to unblock all

of them. Using notify() is preferable (for efficiency) when only one blocked

thread can benefit from the change (for example, when freeing a buffer back into

a pool). notifyAll() is necessary (for correctness) if multiple threads should

resume (for example, when releasing a "writer" lock on a file might permit all

"readers" to resume).

Why can't I say just abs() or sin() instead of Math.abs() and Math.sin()?

The import statement does not bring methods into your local name space. It lets

you abbreviate class names, but not get rid of them altogether. That's just the way

it works, you'll get used to it. It's really a lot safer this way.

However, there is actually a little trick you can use in some cases that gets you

what you want. If your top-level class doesn't need to inherit from anything else,

make it inherit from java.lang.Math. That *does* bring all the methods into your

local name space. But you can't use this trick in an applet, because you have to

inherit from java.awt.Applet. And actually, you can't use it on java.lang.Math at

all, because Math is a "final" class which means it can't be extended.

Why are there no global variables in Java?

Global variables are considered bad form for a variety of reasons: · Adding state

variables breaks referential transparency (you no longer can understand a

statement or expression on its own: you need to understand it in the context of the

settings of the global variables).

· State variables lessen the cohesion of a program: you need to know more to

© Copyright : IT Engg Portal – www.itportal.in 103

understand how something works. A major point of Object-Oriented

programming is to break up global state into more easily understood collections

of local state.

· When you add one variable, you limit the use of your program to one instance.

What you thought was global, someone else might think of as local: they may

want to run two copies of your program at once.

For these reasons, Java decided to ban global variables.

What does it mean that a class or member is final? A final class can no longer be subclassed. Mostly this is done for security reasons

with basic classes like String and Integer. It also allows the compiler to make

some optimizations, and makes thread safety a little easier to achieve. Methods

may be declared final as well. This means they may not be overridden in a

subclass.

Fields can be declared final, too. However, this has a completely different

meaning. A final field cannot be changed after it's initialized, and it must include

an initializer statement where it's declared. For example,

public final double c = 2.998;

It's also possible to make a static field final to get the effect of C++'s const

statement or some uses of C's #define, e.g. public static final double c = 2.998;

What does it mean that a method or class is abstract?

An abstract class cannot be instantiated. Only its subclasses can be instantiated.

You indicate that a class is abstract with the abstract keyword like this:

public abstract class Container extends Component {

Abstract classes may contain abstract methods. A method declared abstract is not

actually implemented in the current class. It exists only to be overridden in

subclasses. It has no body. For example,

public abstract float price();

Abstract methods may only be included in abstract classes. However, an abstract

class is not required to have any abstract methods, though most of them do.

Each subclass of an abstract class must override the abstract methods of its

superclasses or itself be declared abstract.

What is the main difference between Java platform and other platforms? The Java platform differs from most other platforms in that it's a software-only

platform that runs on top of other hardware-based platforms.

© Copyright : IT Engg Portal – www.itportal.in 104

The Java platform has three elements:

Java programming language

The Java Virtual Machine (Java VM)

The Java Application Programming Interface (Java API)

What is the Java Virtual Machine? The Java Virtual Machine is a software that can be ported onto various hardware-

based platforms.

What is the Java API? The Java API is a large collection of ready-made software components that

provide many useful capabilities, such as graphical user interface (GUI) widgets.

What is the package?

The package is a Java namespace or part of Java libraries. The Java API is

grouped into libraries of related classes and interfaces; these libraries are known

as packages.

What is native code? The native code is code that after you compile it, the compiled code runs on a

specific hardware platform.

Explain the user defined Exceptions? User defined Exceptions are the separate Exception classes defined by the user

for specific purposed. An user defined can created by simply sub-classing it to the

Exception class. This allows custom exceptions to be generated (using throw) and

caught in the same way as normal exceptions.

Example:

class myCustomException extends Exception {

// The class simply has to exist to be an exception

}

Is Java code slower than native code? Not really. As a platform-independent environment, the Java platform can be a bit

slower than native code. However, smart compilers, well-tuned interpreters, and

just-in-time bytecode compilers can bring performance close to that of native

code without threatening portability.

© Copyright : IT Engg Portal – www.itportal.in 105

Can main() method be overloaded? Yes. the main() method is a special method for a program entry. You can

overload main() method in any ways. But if you change the signature of the main

method, the entry point for the program will be gone.

What is the serialization?

The serialization is a kind of mechanism that makes a class or a bean persistence

by having its properties or fields and state information saved and restored to and

from storage.

Explain the new Features of JDBC 2.0 Core API? The JDBC 2.0 API includes the complete JDBC API, which includes both core

and Optional Package API, and provides inductrial-strength database computing

capabilities.

New Features in JDBC 2.0 Core API:

Scrollable result sets- using new methods in the ResultSet interface allows

programmatically move the to particular row or to a position relative to its current

position

JDBC 2.0 Core API provides the Batch Updates functionality to the java

applications.

Java applications can now use the ResultSet.updateXXX methods.

New data types - interfaces mapping the SQL3 data types

Custom mapping of user-defined types (UTDs)

Miscellaneous features, including performance hints, the use of character streams,

full precision for java.math.BigDecimal values, additional security, and support

for time zones in date, time, and timestamp values.

How you can force the garbage collection? Garbage collection automatic process and can't be forced.

Explain garbage collection?

Garbage collection is one of the most important feature of Java. Garbage

collection is also called automatic memory management as JVM automatically

removes the unused variables/objects (value is null) from the memory. User

program cann't directly free the object from memory, instead it is the job of the

garbage collector to automatically free the objects that are no longer referenced

by a program. Every class inherits finalize() method from java.lang.Object, the

© Copyright : IT Engg Portal – www.itportal.in 106

finalize() method is called by garbage collector when it determines no more

references to the object exists. In Java, it is good idea to explicitly assign null into

a variable when no more in use. I Java on calling System.gc() and Runtime.gc(),

JVM tries to recycle the unused objects, but there is no guarantee when all the

objects will garbage collected.

Describe the principles of OOPS. There are three main principals of oops which are called Polymorphism,

Inheritance and Encapsulation.

Explain the Encapsulation principle. Encapsulation is a process of binding or wrapping the data and the codes that

operates on the data into a single entity. This keeps the data safe from outside

interface and misuse. One way to think about encapsulation is as a protective

wrapper that prevents code and data from being arbitrarily accessed by other code

defined outside the wrapper.

Explain the Inheritance principle. Inheritance is the process by which one object acquires the properties of another

object.

Explain the Polymorphism principle.

The meaning of Polymorphism is something like one name many forms.

Polymorphism enables one entity to be used as as general category for different

types of actions. The specific action is determined by the exact nature of the

situation. The concept of polymorphism can be explained as "one interface,

multiple methods".

Explain the different forms of Polymorphism. From a practical programming viewpoint, polymorphism exists in three distinct

forms in Java:

Method overloading

Method overriding through inheritance

Method overriding through the Java interface

What are Access Specifiers available in Java? ccess specifiers are keywords that determines the type of access to the member of

a class. These are:

© Copyright : IT Engg Portal – www.itportal.in 107

Public

Protected

Private

Defaults

Describe the wrapper classes in Java. Wrapper class is wrapper around a primitive data type. An instance of a wrapper

class contains, or wraps, a primitive value of the corresponding type.

Following table lists the primitive types and the corresponding wrapper classes:

Primitive Wrapper

boolean java.lang.Boolean

byte java.lang.Byte

char java.lang.Character

double java.lang.Double

float java.lang.Float

int java.lang.Integer

long java.lang.Long

short java.lang.Short

void java.lang.Void

Question: Read the following program:

public class test {

public static void main(String [] args) {

int x = 3;

int y = 1;

if (x = y)

System.out.println("Not equal");

else

System.out.println("Equal");

}

}

What is the result?

A. The output is “Equal”

B. The output in “Not Equal”

© Copyright : IT Engg Portal – www.itportal.in 108

C. An error at " if (x = y)" causes compilation to fall.

D. The program executes but no output is show on console.

Answer: C

Use the Externalizable interface when you need complete control over your

Bean's serialization (for example, when writing and reading a specific file

format). No. Earlier order is maintained.

The superclass constructor runs before the subclass constructor. The

subclass's version of the overridable method will be invoked before the

subclass's constructor has been invoked. If the subclass's overridable method

depends on the proper initialization of the subclass (through the subclass

constructor), the method will most likely fail. Is that true?

Yes. It is true

Why are the interfaces more flexible than abstract classes? --An interface-defined type can be implemented by any class in a class hierarchy

and can be extended by another interface. In contrast, an abstract-class-defined

type can be implemented only by classes that subclass the abstract class.

--An interface-defined type can be used well in polymorphism. The so-called

interface type vs. implementation types.

--Abstract classes evolve more easily than interfaces. If you add a new concrete

method to an abstract class, the hierarchy system is still working. If you add a

method to an interface, the classes that rely on the interface will break when

recompiled.

--Generally, use interfaces for flexibility; use abstract classes for ease of

evolution (like expanding class functionality).

What are new language features in J2SE 5.0? Generally:

1. generics

2. static imports

3. annotations

4. typesafe enums

5. enhanced for loop

6. autoboxing/unboxing

© Copyright : IT Engg Portal – www.itportal.in 109

7. varargs

8. covariant return types

What is covariant return type?

A covariant return type lets you override a superclass method with a return type

that subtypes the superclass method's return type. So we can use covariant return

types to minimize upcasting and downcasting.

class Parent {

Parent foo () {

System.out.println ("Parent foo() called");

return this;

}

}

class Child extends Parent {

Child foo () {

System.out.println ("Child foo() called");

return this;

}

}

class Covariant {

public static void main(String[] args) {

Child c = new Child();

Child c2 = c.foo(); // c2 is Child

Parent c3 = c.foo(); // c3 points to Child

}

}

What is the result of the following statement? int i = 1, float f = 2.0f;

i += f; //ok, the cast done automatically by the compiler

i = i + f; //error

The compound assignment operators automatically include cast operations in

their behaviors.

© Copyright : IT Engg Portal – www.itportal.in 110

What is externalization? Where is it useful?

Use the Externalizable interface when you need complete control over your

Bean's serialization (for example, when writing and reading a specific file

format).

What will be the output on executing the following code.

public class MyClass {

public static void main (String args[] ) {

int abc[] = new int [5];

System.out.println(abc);

}

}

A Error array not initialized

B 5

C null

D Print some junk characters

Answer : D

It will print some junk characters to the output. Here it will not give any compile

time or runtime error because we have declared and initialized the array properly.

Event if we are not assigning a value to the array, it will always initialized to its

defaults.

What will be the output on executing the following code.

public class MyClass {

public static void main (String args[] ) {

int abc[] = new int [5];

System.out.println(abc[0]);

}

}

© Copyright : IT Engg Portal – www.itportal.in 111

A Error array not initialized

B 5

C 0

D Print some junk characters

Answer : C.

What is a marker interface ?

An interface that contains no methods. E.g.: Serializable, Cloneable,

SingleThreadModel etc. It is used to just mark java classes that support certain

capability.

What are tag interfaces? Tag interface is an alternate name for marker interface.

What are the restrictions placed on static method ? We cannot override static methods. We cannot access any object variables inside

static method. Also the this reference also not available in static methods.

What is JVM? JVM stands for Java Virtual Machine. It is the run time for java programs. All are

java programs are running inside this JVM only. It converts java byte code to OS

specific commands. In addition to governing the execution of an application's

byte codes, the virtual machine handles related tasks such as managing the

system's memory, providing security against malicious code, and managing

multiple threads of program execution.

What is JIT?

JIT stands for Just In Time compiler. It compiles java byte code to native code.

What are ClassLoaders? 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.

Every Class object contains a reference to the ClassLoader that defined it.

Class objects for array classes are not created by class loaders, but are created

© Copyright : IT Engg Portal – www.itportal.in 112

automatically as required by the Java runtime. The class loader for an array class,

as returned by Class.getClassLoader() is the same as the class loader for its

element type; if the element type is a primitive type, then the array class has no

class loader.

Applications implement subclasses of ClassLoader in order to extend the manner

in which the Java virtual machine dynamically loads classes.

What is Service Locator pattern? The Service Locator pattern locates J2EE (Java 2 Platform, Enterprise Edition)

services for clients and thus abstracts the complexity of network operation and

J2EE service lookup as EJB (Enterprise JavaBean) Interview Questions - Home

and JMS (Java Message Service) component factories. The Service Locator hides

the lookup process's implementation details and complexity from clients. To

improve application performance, Service Locator caches service objects to

eliminate unnecessary JNDI (Java Naming and Directory Interface) activity that

occurs in a lookup operation.

What is Session Facade pattern? Session facade is one design pattern that is often used while developing enterprise

applications. It is implemented as a higher level component (i.e.: Session EJB),

and it contains all the iteractions between low level components (i.e.: Entity EJB).

It then provides a single interface for the functionality of an application or part of

it, and it decouples lower level components simplifying the design. Think of a

bank situation, where you have someone that would like to transfer money from

one account to another. In this type of scenario, the client has to check that the

user is authorized, get the status of the two accounts, check that there are enough

money on the first one, and then call the transfer. The entire transfer has to be

done in a single transaction otherwise is something goes south, the situation has

to be restored.

As you can see, multiple server-side objects need to be accessed and possibly

modified. Multiple fine-grained invocations of Entity (or even Session) Beans

add the overhead of network calls, even multiple transaction. In other words, the

risk is to have a solution that has a high network overhead, high coupling, poor

reusability and mantainability.

The best solution is then to wrap all the calls inside a Session Bean, so the clients

will have a single point to access (that is the session bean) that will take care of

handling all the rest.

© Copyright : IT Engg Portal – www.itportal.in 113

What is Data Access Object pattern?

The Data Access Object (or DAO) pattern: separates a data resource's client

interface from its data access mechanisms adapts a specific data resource's access

API to a generic client interface

The DAO pattern allows data access mechanisms to change independently of the

code that uses the data.

The DAO implements the access mechanism required to work with the data

source. The data source could be a persistent store like an RDBMS, an external

service like a B2B exchange, a repository like an LDAP database, or a business

service accessed via CORBA Internet Inter-ORB Protocol (IIOP) or low-level

sockets. The business component that relies on the DAO uses the simpler

interface exposed by the DAO for its clients. The DAO completely hides the data

source implementation details from its clients. Because the interface exposed by

the DAO to clients does not change when the underlying data source

implementation changes, this pattern allows the DAO to adapt to different storage

schemes without affecting its clients or business components. Essentially, the

DAO acts as an adapter between the component and the data source.

Can we make an EJB singleton? This is a debatable question, and for every answer we propose there can be

contradictions. I propose 2 solutions of the same. Remember that EJB's are

distributed components and can be deployed on different JVM's in a Distributed

environment

i) Follow the steps as given below

Make sure that your serviceLocator is deployed on only one JVM.

In the serviceLocator create a HashTable/HashMap(You are the right judge to

choose between these two)

When ever a request comes for an EJB to a serviceLocator, it first checks in the

HashTable if an entry already exists in the table with key being the JNDI name of

EJB. If key is present and value is not null, return the existing reference, else

lookup the EJB in JNDI as we do normally and add an entry into the Hashtable

before returning it to the client. This makes sure that you maintain a singleton of

EJB.

ii) In distributed environment our components/Java Objects would be running on

different JVM's. So the normal singleton code we write for maintaining single

instance works fine for single JVM, but when the class could be loaded in

multiple JVM's and Instantiated in multiple JVM's normal singleton code does

© Copyright : IT Engg Portal – www.itportal.in 114

not work. This is because the ClassLoaders being used in the different JVM's are

different from each other and there is no defined mechanism to check and

compare what is loaded in another JVM. A solution could be(Not tested yet. Need

your feedback on this) to write our own ClassLoader and pass this classLoader as

argument, whenever we are creating a new Instance and make sure that only one

instance is created for the proposed class. This can be done easily.

How can we make a class Singleton ?

A) If the class is Serializable

class Singleton implements Serializable

{

private static Singleton instance;

private Singleton() { }

public static synchronized Singleton getInstance()

{

if (instance == null)

instance = new Singleton();

return instance;

}

/**

If the singleton implements Serializable, then this

* method must be supplied.

*/

protected Object readResolve() {

return instance;

}

/**

This method avoids the object fro being cloned

*/

public Object clone() {

throws CloneNotSupportedException ;

//return instance;

© Copyright : IT Engg Portal – www.itportal.in 115

}

}

B) If the class is NOT Serializable

class Singleton

{

private static Singleton instance;

private Singleton() { }

public static synchronized Singleton getInstance()

{

if (instance == null)

instance = new Singleton();

return instance;

}

/**

This method avoids the object from being cloned

**/

public Object clone() {

throws CloneNotSupportedException ;

//return instance;

}

}

How is static Synchronization different form non-static synchronization?

When Synchronization is applied on a static Member or a static block, the lock is

performed on the Class and not on the Object, while in the case of a Non-static

block/member, lock is applied on the Object and not on class. [Trail 2: There is a

class called Class in Java whose object is associated with the object(s) of your

class. All the static members declared in your class will have reference in this

class(Class). As long as your class exists in memory this object of Class is also

present. Thats how even if you create multiple objects of your class only one

Class object is present and all your objects are linked to this Class object. Even

though one of your object is GCed after some time, this object of Class is not

© Copyright : IT Engg Portal – www.itportal.in 116

GCed untill all the objects associated with it are GCed.

This means that when ever you call a "static synchronized" block, JVM locks

access to this Class object and not any of your objects. Your client can till access

the non-static members of your objects.

What are class members and Instance members? Any global members(Variables, methods etc.) which are static are called as Class

level members and those which are non-static are called as Instance level

members.

Name few Garbage collection algorithms?

Here they go:

Mark and Sweep

Reference counting

Tracing collectors

Copying collectors

Heap compaction

Mark-compact collectors

Can we force Garbage collection? java follows a philosophy of automatic garbage collection, you can suggest or

encourage the JVM to perform garbage collection but you can not force it. Once a

variable is no longer referenced by anything it is available for garbage collection.

You can suggest garbage collection with System.gc(), but this does not guarantee

when it will happen. Local variables in methods go out of scope when the method

exits. At this point the methods are eligible for garbage collection. Each time the

method comes into scope the local variables are re-created.

Does Java pass by Value or reference?

Its uses Reference while manipulating objects but pass by value when sending

method arguments. Those who feel why I added this simple question in this

section while claiming to be maintaining only strong and interesting questions, go

ahead and answer following questions.

a)What is the out put of:

import java.util.*;

class TestCallByRefWithObject

© Copyright : IT Engg Portal – www.itportal.in 117

{

ArrayList list = new ArrayList(5);

public void remove(int index){

list.remove(index);

}

public void add(Object obj){

list.add(obj);

}

public void display(){

System.out.println(list);

}

public static void main(String[] args)

{

TestCallByRefWithObject test = new TestCallByRefWithObject();

test.add("1");

test.add("2");

test.add("3");

test.add("4");

test.add("5");

test.remove(4);

test.display();

}

}

b) And now what is the output of:

import java.util.*;

class TestCallByRefWithInt

© Copyright : IT Engg Portal – www.itportal.in 118

{

int i = 5;

public void decrement(int i){

i--;

}

public void increment(int i){

i++;

}

public void display(){

System.out.println("\nValue of i is : " +i);

}

public static void main(String[] args)

{

TestCallByRefWithInt test = new TestCallByRefWithInt();

test.increment(test.i);

test.display();

}

}

Why Thread is faster compare to process? A thread is never faster than a process. If you run a thread(say there's a process

which has spawned only one thread) in one JVM and a process in another and

that both of them require same resources then both of them would take same time

to execute. But, when a program/Application is thread based(remember here there

will be multiple threads running for a single process) then definetly a thread

based appliation/program is faster than a process based application. This is

because, when ever a process requires or waits for a resource CPU takes it out of

the critical section and allocates the mutex to another process.

Before deallocating the ealier one, it stores the context(till what state did it

execute that process) in registers. Now if this deallocated process has to come

© Copyright : IT Engg Portal – www.itportal.in 119

back and execute as it has got the resource for which it was waiting, then it can't

go into critical section directly. CPU asks that process to follow scheduling

algorithm. So this process has to wait again for its turn. While in the case of

thread based application, the application is still with CPU only that thread which

requires some resource goes out, but its co threads(of same process/apllication)

are still in the critical section. Hence it directly comes back to the CPU and does

not wait outside. Hence an application which is thread based is faster than an

application which is process based.

Be sure that its not the competion between thread and process, its between an

application which is thread based or process based.

When and How is an object considered as Garbage by a GC? An object is considered garbage when it can no longer be reached from any

pointer in the running program. The most straightforward garbage collection

algorithms simply iterate over every reachable object. Any objects left over are

then considered garbage.

What are generations in Garbage Collection terminology? What is its

relevance?

Garbage Collectors make assumptions about how our application runs. Most

common assumption is that an object is most likely to die shortly after it was

created: called infant mortality. This assumes that an object that has been around

for a while, will likely stay around for a while. GC organizes objects into

generations (young, tenured, and perm). This tells that if an object lives for more

than certain period of time it is moved from one generation to another

generations( say from young -> tenured -> permanent). Hence GC will be run

more frequently at the young generations and rarely at permanent generations.

This reduces the overhead on GC and gives faster response time.

What is a Throughput Collector? The throughput collector is a generational collector similar to the default collector

but with multiple threads used to do the minor collection. The major collections

are essentially the same as with the default collector. By default on a host with N

CPUs, the throughput collector uses N garbage collector threads in the collection.

The number of garbage collector threads can be controlled with a command line

option.

© Copyright : IT Engg Portal – www.itportal.in 120

When to Use the Throughput Collector? Use the throughput collector when you want to improve the performance of your

application with larger numbers of processors. In the default collector garbage

collection is done by one thread, and therefore garbage collection adds to the

serial execution time of the application. The throughput collector uses multiple

threads to execute a minor collection and so reduces the serial execution time of

the application. A typical situation is one in which the application has a large

number of threads allocating objects. In such an application it is often the case

that a large young generation is needed

What is Aggressive Heap?

The -XX:+AggressiveHeap option inspects the machine resources (size of

memory and number of processors) and attempts to set various parameters to be

optimal for long-running, memory allocation-intensive jobs. It was originally

intended for machines with large amounts of memory and a large number of

CPUs, but in the J2SE platform, version 1.4.1 and later it has shown itself to be

useful even on four processor machines. With this option the throughput collector

(-XX:+UseParallelGC) is used along with adaptive sizing (-

XX:+UseAdaptiveSizePolicy). The physical memory on the machines must be at

least 256MB before Aggressive Heap can be used.

What is a Concurrent Low Pause Collector? The concurrent low pause collector is a generational collector similar to the

default collector. The tenured generation is collected concurrently with this

collector. This collector attempts to reduce the pause times needed to collect the

tenured generation. It uses a separate garbage collector thread to do parts of the

major collection concurrently with the applications threads. The concurrent

collector is enabled with the command line option -

XX:+UseConcMarkSweepGC. For each major collection the concurrent collector

will pause all the application threads for a brief period at the beginning of the

collection and toward the middle of the collection. The second pause tends to be

the longer of the two pauses and multiple threads are used to do the collection

work during that pause. The remainder of the collection is done with a garbage

collector thread that runs concurrently with the application. The minor collections

are done in a manner similar to the default collector, and multiple threads can

optionally be used to do the minor collection.

© Copyright : IT Engg Portal – www.itportal.in 121

When to Use the Concurrent Low Pause Collector? Use the concurrent low pause collector if your application would benefit from

shorter garbage collector pauses and can afford to share processor resources with

the garbage collector when the application is running. Typically applications

which have a relatively large set of long-lived data (a large tenured generation),

and run on machines with two or more processors tend to benefit from the use of

this collector. However, this collector should be considered for any application

with a low pause time requirement. Optimal results have been observed for

interactive applications with tenured generations of a modest size on a single

processor.

What is Incremental Low Pause Collector?

The incremental low pause collector is a generational collector similar to the

default collector. The minor collections are done with the same young generation

collector as the default collector. Do not use either -XX:+UseParallelGC or -

XX:+UseParNewGC with this collector. The major collections are done

incrementally on the tenured generation. This collector (also known as the train

collector) collects portions of the tenured generation at each minor collection. The

goal of the incremental collector is to avoid very long major collection pauses by

doing portions of the major collection work at each minor collection. The

incremental collector will sometimes find that a non-incremental major collection

(as is done in the default collector) is required in order to avoid running out of

memory.

When to Use the Incremental Low Pause Collector? Use the incremental low pause collector when your application can afford to trade

longer and more frequent young generation garbage collection pauses for shorter

tenured generation pauses. A typical situation is one in which a larger tenured

generation is required (lots of long-lived objects), a smaller young generation will

suffice (most objects are short-lived and don't survive the young generation

collection), and only a single processor is available.

How do you enable the concurrent garbage collector on Sun's JVM? -Xconcgc options allows us to use concurrent garbage collector (1.2.2_07+)we

can also use -XX:+UseConcMarkSweepGC which is available beginning with

J2SE 1.4.1.

© Copyright : IT Engg Portal – www.itportal.in 122

What is a platform? A platform is the hardware or software environment in which a program runs.

Most platforms can be described as a combination of the operating system and

hardware, like Windows 2000 and XP, Linux, Solaris, and MacOS.

What is transient variable? 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.

How to make a class or a bean serializable?

By implementing either the java.io.Serializable interface, or the

java.io.Externalizable interface. As long as one class in a class's inheritance

hierarchy implements Serializable or Externalizable, that class is serializable.

What restrictions are placed on method overloading? Two methods may not have the same name and argument list but different return

types.

Name Container classes. Window, Frame, Dialog, FileDialog, Panel, Applet, or ScrollPane

What is the List interface? The List interface provides support for ordered collections of objects.

What is the difference between a Scrollbar and a ScrollPane? A Scrollbar is a Component, but not a Container. A ScrollPane is a Container. A

ScrollPane handles its own events and performs its own scrolling.

What is tunnelling? Tunnelling is a route to somewhere. For example, RMI tunnelling is a way to

make RMI application get through firewall. In CS world, tunnelling means a way

to transfer data.

What is meant by "Abstract Interface"?

First, an interface is abstract. That means you cannot have any implementation in

an interface. All the methods declared in an interface are abstract methods or

signatures of the methods.

© Copyright : IT Engg Portal – www.itportal.in 123

Can Java code be compiled to machine dependent executable file?

Yes. There are many tools out there. If you did so, the generated exe file would

be run in the specific platform, not cross-platform.

Do not use the String contatenation operator in lengthy loops or other places

where performance could suffer. Is that true? Yes.

What method is used to specify a container's layout? The setLayout() method is used to specify a container's layout.

Which containers use a FlowLayout as their default layout? The Panel and Applet classes use the FlowLayout as their default layout.

What state does a thread enter when it terminates its processing? When a thread terminates its processing, it enters the dead state.

What is the Collections API? The Collections API is a set of classes and interfaces that support operations on

collections of objects.

What is the List interface? The List interface provides support for ordered collections of objects.

Is sizeof a keyword? The sizeof operator is not a keyword in Java.

Which class is the superclass for every class. Object.

Which Container method is used to cause a container to be laid out and

redisplayed? validate()

What's the difference between a queue and a stack? Stacks works by last-in-first-out rule (LIFO), while queues use the FIFO rule

What comes to mind when you hear about a young generation in Java? Garbage collection.

© Copyright : IT Engg Portal – www.itportal.in 124

You can create an abstract class that contains only abstract methods. On the

other hand, you can create an interface that declares the same methods. So

can you use abstract classes instead of interfaces?

Sometimes. But your class may be a descendent of another class and in this case

the interface is your only option.

What comes to mind when someone mentions a shallow copy in Java? Object cloning.

If you're overriding the method equals() of an object, which other method

you might also consider? hashCode()

You are planning to do an indexed search in a list of objects. Which of the

two Java collections should you use: ArrayList or LinkedList?

ArrayList

How would you make a copy of an entire Java object with its state? Have this class implement Cloneable interface and call its method clone().

How can you minimize the need of garbage collection and make the memory

use more effective? Use object pooling and weak object references.

There are two classes: A and B. The class B need to inform a class A when

some important event has happened. What Java technique would you use to

implement it? If these classes are threads I'd consider notify() or notifyAll(). For regular classes

you can use the Observer interface.

What access level do you need to specify in the class declaration to ensure

that only classes from the same directory can access it?

You do not need to specify any access level, and Java will use a default package

access level.

What is the difference between an Interface and an Abstract class?

An abstract class can have instance methods that implement a default behavior.

An Interface can only declare constants and instance methods, but cannot

implement default behavior and all methods are implicitly abstract. An interface

© Copyright : IT Engg Portal – www.itportal.in 125

has all public members and no implementation. An abstract class is a class which

may have the usual flavors of class members (private, protected, etc.), but has

some abstract methods.

What is the purpose of garbage collection in Java, and when is it used? The purpose of garbage collection is to identify and discard objects that are no

longer needed by a program so that their resources can be reclaimed and reused.

A Java object is subject to garbage collection when it becomes unreachable to the

program in which it is used.

Describe synchronization in respect to multithreading. With respect to multithreading, synchronization is the capability to control the

access of multiple threads to shared resources. Without synchonization, it is

possible for one thread to modify a shared variable while another thread is in the

process of using or updating same shared variable. This usually leads to

significant errors.

Explain different way of using thread?

The thread could be implemented by using runnable interface or by inheriting

from the Thread class. The former is more advantageous, 'cause when you are

going for multiple inheritance..the only interface can help.

What are pass by reference and passby value?

Pass By Reference means the passing the address itself rather than passing the

value. Passby Value means passing a copy of the value to be passed.

What is HashMap and Map? Map is Interface and Hashmap is class that implements that.

Difference between HashMap and HashTable? The HashMap class is roughly equivalent to Hashtable, except that it is

unsynchronized and permits nulls. (HashMap allows null values as key and value

whereas Hashtable doesnt allow). HashMap does not guarantee that the order of

the map will remain constant over time. HashMap is unsynchronized and

Hashtable is synchronized.

Difference between Vector and ArrayList? Vector is synchronized whereas arraylist is not.

© Copyright : IT Engg Portal – www.itportal.in 126

Difference between Swing and AWT?

AWT are heavy-weight components. Swings are light-weight components. Hence

swing works faster than AWT.

What is the difference between a constructor and a method? A constructor is a member function of a class that is used to create objects of that

class. It has the same name as the class itself, has no return type, and is invoked

using the new operator. A method is an ordinary member function of a class. It

has its own name, a return type (which may be void), and is invoked using the dot

operator.

What is an Iterator? Some of the collection classes provide traversal of their contents via a

java.util.Iterator interface. This interface allows you to walk through a collection

of objects, operating on each object in turn. Remember when using Iterators that

they contain a snapshot of the collection at the time the Iterator was obtained;

generally it is not advisable to modify the collection itself while traversing an

Iterator.

State the significance of public, private, protected, default modifiers both

singly and in combination and state the effect of package relationships on

declared items qualified by these modifiers. public : Public class is visible in other packages, field is visible everywhere (class

must be public too) private : Private variables or methods may be used only by an

instance of the same class that declares the variable or method, A private feature

may only be accessed by the class that owns the feature. protected : Is available to

all classes in the same package and also available to all subclasses of the class

that owns the protected feature. This access is provided even to subclasses that

reside in a different package from the class that owns the protected feature.

default :What you get by default ie, without any access modifier (ie, public

private or protected). It means that it is visible to all within a particular package.

What is an abstract class?

Abstract class must be extended/subclassed (to be useful). It serves as a template.

A class that is abstract may not be instantiated (ie, you may not call its

constructor), abstract class may contain static data. Any class with an abstract

method is automatically abstract itself, and must be declared as such.

© Copyright : IT Engg Portal – www.itportal.in 127

A class may be declared abstract even if it has no abstract methods. This prevents

it from being instantiated.

What is static in java? Static means one per class, not one for each object no matter how many instance

of a class might exist. This means that you can use them without creating an

instance of a class. Static methods are implicitly final, because overriding is done

based on the type of the object, and static methods are attached to a class, not an

object. A static method in a super class can be shadowed by another static method

in a subclass, as long as the original method was not declared final. However, you

can't override a static method with a no static method. In other words, you can't

change a static method into an instance method in a subclass.

What is final? A final class can't be extended ie., final class may not be subclassed. A final

method can't be overridden when its class is inherited. You can't change value of

a final variable (is a constant).

What if the main method is declared as private? The program compiles properly but at runtime it will give "Main method not

public." message.

What if the static modifier is removed from the signature of the main

method? Program compiles. But at runtime throws an error "NoSuchMethodError".

What if I write static public void instead of public static void? Program compiles and runs properly.

What if I do not provide the String array as the argument to the method? Program compiles but throws a runtime error "NoSuchMethodError".

What is the first argument of the String array in main method? The String array is empty. It does not have any element. This is unlike C/C++

where the first element by default is the program name.

If I do not provide any arguments on the command line, then the String

array of Main method will be empty or null? It is empty. But not null.

© Copyright : IT Engg Portal – www.itportal.in 128

How can one prove that the array is not null but empty using one line of

code? Print args.length. It will print 0. That means it is empty. But if it would have been

null then it would have thrown a NullPointerException on attempting to print

args.length.

Can an application have multiple classes having main method?

Yes it is possible. While starting the application we mention the class name to be

run. The JVM will look for the Main method only in the class whose name you

have mentioned. Hence there is not conflict amongst the multiple classes having

main method.

Can I have multiple main methods in the same class? No the program fails to compile. The compiler says that the main method is

already defined in the class.

Do I need to import java.lang package any time? Why ?

No. It is by default loaded internally by the JVM.

Can I import same package/class twice? Will the JVM load the package

twice at runtime? One can import the same package or same class multiple times. Neither compiler

nor JVM complains abt it. And the JVM will internally load the class only once

no matter how many times you import the same class.

What are Checked and UnChecked Exception? A checked exception is some subclass of Exception (or Exception itself),

excluding class RuntimeException and its subclasses. Making an exception

checked forces client programmers to deal with the possibility that the exception

will be thrown. eg, IOException thrown by java.io.FileInputStream's read()

method· Unchecked exceptions are RuntimeException and any of its subclasses.

Class Error and its subclasses also are unchecked. With an unchecked exception,

however, the compiler doesn't force client programmers either to catch the

exception or declare it in a throws clause. In fact, client programmers may not

even know that the exception could be thrown. eg,

StringIndexOutOfBoundsException thrown by String's charAt() method·

Checked exceptions must be caught at compile time. Runtime exceptions do not

need to be. Errors often cannot be.

© Copyright : IT Engg Portal – www.itportal.in 129

What is Overriding?

When a class defines a method using the same name, return type, and arguments

as a method in its superclass, the method in the class overrides the method in the

superclass.

When the method is invoked for an object of the class, it is the new definition of

the method that is called, and not the method definition from superclass. Methods

may be overridden to be more public, not more private.

What are different types of inner classes? Nested top-level classes, Member classes, Local classes, Anonymous classes

Nested top-level classes- If you declare a class within a class and specify the

static modifier, the compiler treats the class just like any other top-level class.

Any class outside the declaring class accesses the nested class with the declaring

class name acting similarly to a package. eg, outer.inner. Top-level inner classes

implicitly have access only to static variables.There can also be inner interfaces.

All of these are of the nested top-level variety.

Member classes - Member inner classes are just like other member methods and

member variables and access to the member class is restricted, just like methods

and variables. This means a public member class acts similarly to a nested top-

level class. The primary difference between member classes and nested top-level

classes is that member classes have access to the specific instance of the

enclosing class.

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 a more

publicly available interface.Because local classes are not members, the modifiers

public, protected, private, and static are not usable.

Anonymous classes - Anonymous inner classes extend local inner classes one

level further. As anonymous classes have no name, you cannot provide a

constructor.

Are the imports checked for validity at compile time? e.g. will the code

containing an import such as java.lang.ABCD compile?

© Copyright : IT Engg Portal – www.itportal.in 130

Yes the imports are checked for the semantic validity at compile time. The code

containing above line of import will not compile. It will throw an error saying,can

not resolve symbol

symbol : class ABCD

location: package io

import java.io.ABCD;

Does importing a package imports the subpackages as well? e.g. Does

importing com.MyTest.* also import com.MyTest.UnitTests.*?

No you will have to import the subpackages explicitly. Importing com.MyTest.*

will import classes in the package MyTest only. It will not import any class in any

of it's subpackage.

What is the difference between declaring a variable and defining a variable? In declaration we just mention the type of the variable and it's name. We do not

initialize it. But defining means declaration + initialization.

e.g String s; is just a declaration while String s = new String ("abcd"); Or String s

= "abcd"; are both definitions.

What is the default value of an object reference declared as an instance

variable? Null unless we define it explicitly.

Can a top level class be private or protected?

No. A top level class can not be private or protected. It can have either "public" or

no modifier. If it does not have a modifier it is supposed to have a default

access.If a top level class is declared as private the compiler will complain that

the "modifier private is not allowed here". This means that a top level class can

not be private. Same is the case with protected.

What type of parameter passing does Java support? In Java the arguments are always passed by value .

Primitive data types are passed by reference or pass by value? Primitive data types are passed by value.

Objects are passed by value or by reference? Java only supports pass by value. With objects, the object reference itself is

© Copyright : IT Engg Portal – www.itportal.in 131

passed by value and so both the original reference and parameter copy both refer

to the same object .

What is serialization? Serialization is a mechanism by which you can save the state of an object by

converting it to a byte stream.

How do I serialize an object to a file?

The class whose instances are to be serialized should implement an interface

Serializable. Then you pass the instance to the ObjectOutputStream which is

connected to a fileoutputstream. This will save the object to a file.

Which methods of Serializable interface should I implement? The serializable interface is an empty interface, it does not contain any methods.

So we do not implement any methods.

How can I customize the serialization process? i.e. how can one have a

control over the serialization process? Yes it is possible to have control over serialization process. The class should

implement Externalizable interface. This interface contains two methods namely

readExternal and writeExternal. You should implement these methods and write

the logic for customizing the serialization process.

What is the common usage of serialization? Whenever an object is to be sent over the network, objects need to be serialized.

Moreover if the state of an object is to be saved, objects need to be serilized.

What is Externalizable interface? Externalizable is an interface which contains two methods readExternal and

writeExternal. These methods give you a control over the serialization

mechanism. Thus if your class implements this interface, you can customize the

serialization process by implementing these methods.

When you serialize an object, what happens to the object references included

in the object? The serialization mechanism generates an object graph for serialization. Thus it

determines whether the included object references are serializable or not. This is a

© Copyright : IT Engg Portal – www.itportal.in 132

recursive process. Thus when an object is serialized, all the included objects are

also serialized alongwith the original obect.

What one should take care of while serializing the object? One should make sure that all the included objects are also serializable. If any of

the objects is not serializable then it throws a NotSerializableException.

What happens to the static fields of a class during serialization?

There are three exceptions in which serialization doesnot necessarily read and

write to the stream. These are

1. Serialization ignores static fields, because they are not part of ay particular

state state.

2. Base class fields are only hendled if the base class itself is serializable.

3. Transient fields.

Does Java provide any construct to find out the size of an object? No there is not sizeof operator in Java. So there is not direct way to determine the

size of an object directly in Java.

What are wrapper classes? Java provides specialized classes corresponding to each of the primitive data

types. These are called wrapper classes. They are e.g. Integer, Character, Double

etc.

Give a simplest way to find out the time a method takes for execution

without using any profiling tool?

Read the system time just before the method is invoked and immediately after

method returns. Take the time difference, which will give you the time taken by a

method for execution.

To put it in code...

long start = System.currentTimeMillis ();

method ();

long end = System.currentTimeMillis ();

System.out.println ("Time taken for execution is " + (end - start));

Remember that if the time taken for execution is too small, it might show that it is

© Copyright : IT Engg Portal – www.itportal.in 133

taking zero milliseconds for execution. Try it on a method which is big enough, in

the sense the one which is doing considerable amount of processing.

Why do we need wrapper classes? It is sometimes easier to deal with primitives as objects. Moreover most of the

collection classes store objects and not primitive data types. And also the wrapper

classes provide many utility methods also. Because of these reasons we need

wrapper classes. And since we create instances of these classes we can store them

in any of the collection classes and pass them around as a collection. Also we can

pass them around as method parameters where a method expects an object.

What are checked exceptions? Checked exception are those which the Java compiler forces you to catch. e.g.

IOException are checked Exceptions.

What are runtime exceptions?

Runtime exceptions are those exceptions that are thrown at runtime because of

either wrong input data or because of wrong business logic etc. These are not

checked by the compiler at compile time.

What is the difference between error and an exception? An error is an irrecoverable condition occurring at runtime. Such as

OutOfMemory error. These JVM errors and you can not repair them at runtime.

While exceptions are conditions that occur because of bad input etc. e.g.

FileNotFoundException will be thrown if the specified file does not exist. Or a

NullPointerException will take place if you try using a null reference. In most of

the cases it is possible to recover from an exception (probably by giving user a

feedback for entering proper values etc.).

How to create custom exceptions? Your class should extend class Exception, or some more specific type thereof.

If I want an object of my class to be thrown as an exception object, what

should I do? The class should extend from Exception class. Or you can extend your class from

some more precise exception type also.

© Copyright : IT Engg Portal – www.itportal.in 134

If my class already extends from some other class what should I do if I want

an instance of my class to be thrown as an exception object? One can not do anything in this scenario. Because Java does not allow multiple

inheritance and does not provide any exception interface as well.

How does an exception permeate through the code?

An unhandled exception moves up the method stack in search of a matching

When an exception is thrown from a code which is wrapped in a try block

followed by one or more catch blocks, a search is made for matching catch block.

If a matching type is found then that block will be invoked. If a matching type is

not found then the exception moves up the method stack and reaches the caller

method. Same procedure is repeated if the caller method is included in a try catch

block. This process continues until a catch block handling the appropriate type of

exception is found. If it does not find such a block then finally the program

terminates.

What are the different ways to handle exceptions? There are two ways to handle exceptions,

1. By wrapping the desired code in a try block followed by a catch block to catch

the exceptions. and

2. List the desired exceptions in the throws clause of the method and let the caller

of the method handle those exceptions.

What is the basic difference between the 2 approaches to exception handling.

1. try catch block and

2. specifying the candidate exceptions in the throws clause?

When should you use which approach? In the first approach as a programmer of the method, you yourself are dealing

with the exception. This is fine if you are in a best position to decide should be

done in case of an exception. Whereas if it is not the responsibility of the method

to deal with it's own exceptions, then do not use this approach. In this case use the

second approach. In the second approach we are forcing the caller of the method

to catch the exceptions, that the method is likely to throw. This is often the

approach library creators use. They list the exception in the throws clause and we

must catch them. You will find the same approach throughout the java libraries

we use.

© Copyright : IT Engg Portal – www.itportal.in 135

Is it necessary that each try block must be followed by a catch block?

It is not necessary that each try block must be followed by a catch block. It should

be followed by either a catch block OR a finally block. And whatever exceptions

are likely to be thrown should be declared in the throws clause of the method.

If I write return at the end of the try block, will the finally block still

execute? Yes even if you write return as the last statement in the try block and no

exception occurs, the finally block will execute. The finally block will execute

and then the control return.

If I write System.exit (0); at the end of the try block, will the finally block

still execute? No in this case the finally block will not execute because when you say

System.exit (0); the control immediately goes out of the program, and thus finally

never executes.

How are Observer and Observable used? Objects that subclass the Observable class maintain a list of observers. When an

Observable object is updated it invokes the update() method of each of its

observers to notify the observers that it has changed state. The Observer interface

is implemented by objects that observe Observable objects.

What is synchronization and why is it important? With respect to multithreading, synchronization is the capability to control the

access of multiple threads to shared resources. Without synchronization, it is

possible for one thread to modify a shared object while another thread is in the

process of using or updating that object's value. This often leads to significant

errors.

How does Java handle integer overflows and underflows?

It uses those low order bytes of the result that can fit into the size of the type

allowed by the operation.

Does garbage collection guarantee that a program will not run out of

memory? Garbage collection does not guarantee that a program will not run out of memory.

It is possible for programs to use up memory resources faster than they are

© Copyright : IT Engg Portal – www.itportal.in 136

garbage collected. It is also possible for programs to create objects that are not

subject to garbage collection .

What is the difference between preemptive scheduling and time slicing? Under preemptive scheduling, the highest priority task executes until it enters the

waiting or dead states or a higher priority task comes into existence. Under time

slicing, a task executes for a predefined slice of time and then reenters the pool of

ready tasks. The scheduler then determines which task should execute next, based

on priority and other factors.

When a thread is created and started, what is its initial state? A thread is in the ready state after it has been created and started.

What is the purpose of finalization? The purpose of finalization is to give an unreachable object the opportunity to

perform any cleanup processing before the object is garbage collected.

What is the Locale class? The Locale class is used to tailor program output to the conventions of a

particular geographic, political, or cultural region.

What is the difference between a while statement and a do statement? A while statement checks at the beginning of a loop to see whether the next loop

iteration should occur. A do statement checks at the end of a loop to see whether

the next iteration of a loop should occur. The do statement will always execute

the body of a loop at least once.

What is the difference between static and non-static variables?

A static variable is associated with the class as a whole rather than with specific

instances of a class. Non-static variables take on unique values with each object

instance.

How are this() and super() used with constructors? This() is used to invoke a constructor of the same class. super() is used to invoke

a superclass constructor.

What are synchronized methods and synchronized statements? Synchronized methods are methods that are used to control access to an object. A

thread only executes a synchronized method after it has acquired the lock for the

© Copyright : IT Engg Portal – www.itportal.in 137

method's object or class. Synchronized statements are similar to synchronized

methods. A synchronized statement can only be executed after a thread has

acquired the lock for the object or class referenced in the synchronized statement.

What is daemon thread and which method is used to create the daemon

thread? Daemon thread is a low priority thread which runs intermittently in the back

ground doing the garbage collection operation for the java runtime system.

setDaemon method is used to create a daemon thread.

Can applets communicate with each other?

At this point in time applets may communicate with other applets running in the

same virtual machine. If the applets are of the same class, they can communicate

via shared static variables. If the applets are of different classes, then each will

need a reference to the same class with static variables. In any case the basic idea

is to pass the information back and forth through a static variable.

An applet can also get references to all other applets on the same page using the

getApplets() method of java.applet.AppletContext. Once you get the reference to

an applet, you can communicate with it by using its public members.

It is conceivable to have applets in different virtual machines that talk to a server

somewhere on the Internet and store any data that needs to be serialized there.

Then, when another applet needs this data, it could connect to this same server.

Implementing this is non-trivial.

What are the steps in the JDBC connection?

While making a JDBC connection we go through the following steps :

Step 1 : Register the database driver by using :

Class.forName(\" driver classs for that specific database\" );

Step 2 : Now create a database connection using :

Connection con = DriverManager.getConnection(url,username,password);

Step 3: Now Create a query using :

Statement stmt = Connection.Statement(\"select * from TABLE NAME\");

Step 4 : Exceute the query :

stmt.exceuteUpdate();

© Copyright : IT Engg Portal – www.itportal.in 138

How does a try statement determine which catch clause should be used to

handle an exception? When an exception is thrown within the body of a try statement, the catch clauses

of the try statement are examined in the order in which they appear. The first

catch clause that is capable of handling the exceptionis executed. The remaining

catch clauses are ignored.

Can an unreachable object become reachable again? An unreachable object may become reachable again. This can happen when the

object's finalize() method is invoked and the object performs an operation which

causes it to become accessible to reachable objects.

What method must be implemented by all threads? All tasks must implement the run() method, whether they are a subclass of Thread

or implement the Runnable interface.

What are synchronized methods and synchronized statements? Synchronized methods are methods that are used to control access to an object. A

thread only executes a synchronized method after it has acquired the lock for the

method's object or class. Synchronized statements are similar to synchronized

methods. A synchronized statement can only be executed after a thread has

acquired the lock for the object or class referenced in the synchronized statement.

What is Externalizable? Externalizable is an Interface that extends Serializable Interface. And sends data

into Streams in Compressed Format. It has two methods,

writeExternal(ObjectOuput out) and readExternal(ObjectInput in)

What modifiers are allowed for methods in an Interface? Only public and abstract modifiers are allowed for methods in interfaces.

What are some alternatives to inheritance? Delegation is an alternative to inheritance. Delegation means that you include an

instance of another class as an instance variable, and forward messages to the

instance. It is often safer than inheritance because it forces you to think about

each message you forward, because the instance is of a known class, rather than a

© Copyright : IT Engg Portal – www.itportal.in 139

new class, and because it doesn't force you to accept all the methods of the super

class: you can provide only the methods that really make sense. On the other

hand, it makes you write more code, and it is harder to re-use (because it is not a

subclass).

What does it mean that a method or field is "static"?

Static variables and methods are instantiated only once per class. In other words

they are class variables, not instance variables. If you change the value of a static

variable in a particular object, the value of that variable changes for all instances

of that class.

Static methods can be referenced with the name of the class rather than the name

of a particular object of the class (though that works too). That's how library

methods like System.out.println() work out is a static field in the

java.lang.System class.

What is the difference between preemptive scheduling and time slicing? Under preemptive scheduling, the highest priority task executes until it enters the

waiting or dead states or a higher priority task comes into existence. Under time

slicing, a task executes for a predefined slice of time and then reenters the pool of

ready tasks. The scheduler then determines which task should execute next, based

on priority and other factors.

What is the catch or declare rule for method declarations? If a checked exception may be thrown within the body of a method, the method

must either catch the exception or declare it in its throws clause.

Is Empty .java file a valid source file?

Yes, an empty .java file is a perfectly valid source file.

Can a .java file contain more than one java classes? Yes, a .java file contain more than one java classes, provided at the most one of

them is a public class.

Is String a primitive data type in Java? No String is not a primitive data type in Java, even though it is one of the most

© Copyright : IT Engg Portal – www.itportal.in 140

extensively used object. Strings in Java are instances of String class defined in

java.lang package.

Is main a keyword in Java? No, main is not a keyword in Java.

Is next a keyword in Java? No, next is not a keyword.

Is delete a keyword in Java? No, delete is not a keyword in Java. Java does not make use of explicit

destructors the way C++ does.

Is exit a keyword in Java? No. To exit a program explicitly you use exit method in System object.

What happens if you don't initialize an instance variable of any of the

primitive types in Java? Java by default initializes it to the default value for that primitive type. Thus an

int will be initialized to 0, a Boolean will be initialized to false.

What will be the initial value of an object reference which is defined as an

instance variable?

The object references are all initialized to null in Java. However in order to do

anything useful with these references, you must set them to a valid object, else

you will get NullPointerException everywhere you try to use such default

initialized references.

What are the different scopes for Java variables? The scope of a Java variable is determined by the context in which the variable is

declared. Thus a java variable can have one of the three scopes at any given point

in time.

1. Instance : - These are typical object level variables, they are initialized to

default values at the time of creation of object, and remain accessible as long as

the object accessible.

© Copyright : IT Engg Portal – www.itportal.in 141

2. Local : - These are the variables that are defined within a method. They remain

accessible only during the course of method execution. When the method finishes

execution, these variables fall out of scope.

3. Static: - These are the class level variables. They are initialized when the class

is loaded in JVM for the first time and remain there as long as the class remains

loaded. They are not tied to any particular object instance.

What is the default value of the local variables? The local variables are not initialized to any default value, neither primitives nor

object references. If you try to use these variables without initializing them

explicitly, the java compiler will not compile the code. It will complain about the

local variable not being initialized..

How many objects are created in the following piece of code? MyClass c1,

c2, c3;

c1 = new MyClass ();

c3 = new MyClass (); Only 2 objects are created, c1 and c3. The reference c2 is only declared and not

initialized.

Can a public class MyClass be defined in a source file named

YourClass.java?

No the source file name, if it contains a public class, must be the same as the

public class name itself with a .java extension.

Can main method be declared final? Yes, the main method can be declared final, in addition to being public static.

What will be the output of the following statement?

System.out.println ("1" + 3); It will print 13.

What will be the default values of all the elements of an array defined as an

instance variable? If the array is an array of primitive types, then all the elements of the array will be

initialized to the default value corresponding to that primitive type. e.g. All the

© Copyright : IT Engg Portal – www.itportal.in 142

elements of an array of int will be initialized to 0, while that of Boolean type will

be initialized to false. Whereas if the array is an array of references (of any type),

all the elements will be initialized to null.

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

© Copyright : IT Engg Portal – www.itportal.in 143

JDBC

Interview Questions

&

Answers

© Copyright : IT Engg Portal – www.itportal.in 144

JDBC Interview Questions and Answers

What is JDBC?

JDBC may stand for Java Database Connectivity. It is also a trade mark. JDBC is a

layer of abstraction that allows users to choose between databases. It allows you to

change to a different database engine and to write to a single API. JDBC allows you to

write database applications in Java without having to concern yourself with the

underlying details of a particular database.

What's the JDBC 3.0 API? The JDBC 3.0 API is the latest update of the JDBC API. It contains many features,

including scrollable result sets and the SQL:1999 data types.

JDBC (Java Database Connectivity) is the standard for communication between a Java

application and a relational database. The JDBC API is released in two versions;

JDBC version 1.22 (released with JDK 1.1.X in package java.sql) and version 2.0

(released with Java platform 2 in packages java.sql and javax.sql). It is a simple and

powerful largely database-independent way of extracting and inserting data to or from

any database.

Does the JDBC-ODBC Bridge support the new features in the JDBC 3.0 API? The JDBC-ODBC Bridge provides a limited subset of the JDBC 3.0 API.

Can the JDBC-ODBC Bridge be used with applets? Use of the JDBC-ODBC bridge from an untrusted applet running in a browser, such as

Netscape Navigator, isn't allowed. The JDBC-ODBC bridge doesn't allow untrusted

code to call it for security reasons. This is good because it means that an untrusted

applet that is downloaded by the browser can't circumvent Java security by calling

ODBC. Remember that ODBC is native code, so once ODBC is called the Java

programming language can't guarantee that a security violation won't occur. On the

other hand, Pure Java JDBC drivers work well with applets. They are fully

downloadable and do not require any client-side configuration.

Finally, we would like to note that it is possible to use the JDBC-ODBC bridge with

applets that will be run in appletviewer since appletviewer assumes that applets are

trusted. In general, it is dangerous to turn applet security off, but it may be appropriate

in certain controlled situations, such as for applets that will only be used in a secure

intranet environment. Remember to exercise caution if you choose this option, and use

an all-Java JDBC driver whenever possible to avoid security problems.

© Copyright : IT Engg Portal – www.itportal.in 145

How do I start debugging problems related to the JDBC API? A good way to find out what JDBC calls are doing is to enable JDBC tracing. The

JDBC trace contains a detailed listing of the activity occurring in the system that is

related to JDBC operations.

If you use the DriverManager facility to establish your database connection, you use

the DriverManager.setLogWriter method to enable tracing of JDBC operations. If you

use a DataSource object to get a connection, you use the DataSource.setLogWriter

method to enable tracing. (For pooled connections, you use the

ConnectionPoolDataSource.setLogWriter method, and for connections that can

participate in distributed transactions, you use the XADataSource.setLogWriter

method.)

What is new in JDBC 2.0? With the JDBC 2.0 API, you will be able to do the following:

Scroll forward and backward in a result set or move to a specific row

(TYPE_SCROLL_SENSITIVE,previous(), last(), absolute(), relative(), etc.)

Make updates to database tables using methods in the Java programming language

instead of using SQL commands.(updateRow(), insertRow(), deleteRow(), etc.)

Send multiple SQL statements to the database as a unit, or batch (addBatch(),

executeBatch())

Use the new SQL3 datatypes as column values like Blob, Clob, Array, Struct, Ref.

How to move the cursor in scrollable resultset ?

a. create a scrollable ResultSet object.

Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,

ResultSet.CONCUR_READ_ONLY);

ResultSet srs = stmt.executeQuery("SELECT COLUMN_1,

COLUMN_2 FROM TABLE_NAME");

b. use a built in methods like afterLast(), previous(), beforeFirst(), etc. to scroll the

resultset.

srs.afterLast();

while (srs.previous()) {

String name = srs.getString("COLUMN_1");

float salary = srs.getFloat("COLUMN_2");

//...

© Copyright : IT Engg Portal – www.itportal.in 146

c. to find a specific row, use absolute(), relative() methods.

srs.absolute(4); // cursor is on the fourth row

int rowNum = srs.getRow(); // rowNum should be 4

srs.relative(-3);

int rowNum = srs.getRow(); // rowNum should be 1

srs.relative(2);

int rowNum = srs.getRow(); // rowNum should be 3

d. use isFirst(), isLast(), isBeforeFirst(), isAfterLast() methods to check boundary

status.

How to update a resultset programmatically? a. create a scrollable and updatable ResultSet object.

Statement stmt = con.createStatement

(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);

ResultSet uprs = stmt.executeQuery("SELECT COLUMN_1,

COLUMN_2 FROM TABLE_NAME");

b. move the cursor to the specific position and use related method to update data and

then, call updateRow() method.

uprs.last();

uprs.updateFloat("COLUMN_2", 25.55);//update last row's data

uprs.updateRow();//don't miss this method, otherwise,

// the data will be lost.

How can I use the JDBC API to access a desktop database like Microsoft Access

over the network? Most desktop databases currently require a JDBC solution that uses ODBC

underneath. This is because the vendors of these database products haven't

implemented all-Java JDBC drivers.

The best approach is to use a commercial JDBC driver that supports ODBC and the

database you want to use. See the JDBC drivers page for a list of available JDBC

drivers.

The JDBC-ODBC bridge from Sun's Java Software does not provide network access

to desktop databases by itself. The JDBC-ODBC bridge loads ODBC as a local DLL,

and typical ODBC drivers for desktop databases like Access aren't networked. The

© Copyright : IT Engg Portal – www.itportal.in 147

JDBC-ODBC bridge can be used together with the RMI-JDBC bridge, however, to

access a desktop database like Access over the net. This RMI-JDBC-ODBC solution is

free.

Are there any ODBC drivers that do not work with the JDBC-ODBC Bridge? Most ODBC 2.0 drivers should work with the Bridge. Since there is some variation in

functionality between ODBC drivers, the functionality of the bridge may be affected.

The bridge works with popular PC databases, such as Microsoft Access and FoxPro.

What causes the "No suitable driver" error? "No suitable driver" is an error that usually occurs during a call to the

DriverManager.getConnection method. The cause can be failing to load the

appropriate JDBC drivers before calling the getConnection method, or it can be

specifying an invalid JDBC URL--one that isn't recognized by your JDBC driver.

Your best bet is to check the documentation for your JDBC driver or contact your

JDBC driver vendor if you suspect that the URL you are specifying is not being

recognized by your JDBC driver.

In addition, when you are using the JDBC-ODBC Bridge, this error can occur if one or

more the the shared libraries needed by the Bridge cannot be loaded. If you think this

is the cause, check your configuration to be sure that the shared libraries are accessible

to the Bridge.

Why isn't the java.sql.DriverManager class being found? This problem can be caused by running a JDBC applet in a browser that supports the

JDK 1.0.2, such as Netscape Navigator 3.0. The JDK 1.0.2 does not contain the JDBC

API, so the DriverManager class typically isn't found by the Java virtual machine

running in the browser.

Here's a solution that doesn't require any additional configuration of your web clients.

Remember that classes in the java.* packages cannot be downloaded by most browsers

for security reasons. Because of this, many vendors of all-Java JDBC drivers supply

versions of the java.sql.* classes that have been renamed to jdbc.sql.*, along with a

version of their driver that uses these modified classes. If you import jdbc.sql.* in your

applet code instead of java.sql.*, and add the jdbc.sql.* classes provided by your

JDBC driver vendor to your applet's codebase, then all of the JDBC classes needed by

the applet can be downloaded by the browser at run time, including the DriverManager

class.

This solution will allow your applet to work in any client browser that supports the

© Copyright : IT Engg Portal – www.itportal.in 148

JDK 1.0.2. Your applet will also work in browsers that support the JDK 1.1, although

you may want to switch to the JDK 1.1 classes for performance reasons. Also, keep in

mind that the solution outlined here is just an example and that other solutions are

possible.

How to insert and delete a row programmatically? (new feature in JDBC 2.0)

Make sure the resultset is updatable.

1. move the cursor to the specific position.

uprs.moveToCurrentRow();

2. set value for each column.

uprs.moveToInsertRow();//to set up for insert

uprs.updateString("col1" "strvalue");

uprs.updateInt("col2", 5);

...

3. call inserRow() method to finish the row insert process.

uprs.insertRow();

To delete a row: move to the specific position and call deleteRow() method:

uprs.absolute(5);

uprs.deleteRow();//delete row 5

To see the changes call refreshRow();

uprs.refreshRow();

What are the two major components of JDBC? One implementation interface for database manufacturers, the other implementation

interface for application and applet writers.

© Copyright : IT Engg Portal – www.itportal.in 149

What is JDBC Driver interface? The JDBC Driver interface provides vendor-specific implementations of the abstract

classes provided by the JDBC API. Each vendor driver must provide implementations

of the java.sql.Connection,Statement,PreparedStatement, CallableStatement, ResultSet

and Driver.

How do I retrieve a whole row of data at once, instead of calling an individual

ResultSet.getXXX method for each column? The ResultSet.getXXX methods are the only way to retrieve data from a ResultSet

object, which means that you have to make a method call for each column of a row. It

is unlikely that this is the cause of a performance problem, however, because it is

difficult to see how a column could be fetched without at least the cost of a function

call in any scenario. We welcome input from developers on this issue.

What are the common tasks of JDBC?

Create an instance of a JDBC driver or load JDBC drivers through jdbc.drivers

Register a driver

Specify a database

Open a database connection

Submit a query

Receive results

Process results

Why does the ODBC driver manager return 'Data source name not found and no

default driver specified Vendor: 0' This type of error occurs during an attempt to connect to a database with the bridge.

First, note that the error is coming from the ODBC driver manager. This indicates that

the bridge-which is a normal ODBC client-has successfully called ODBC, so the

problem isn't due to native libraries not being present. In this case, it appears that the

error is due to the fact that an ODBC DSN (data source name) needs to be configured

on the client machine. Developers often forget to do this, thinking that the bridge will

magically find the DSN they configured on their remote server machine

How to use JDBC to connect Microsoft Access? There is a specific tutorial at javacamp.org. Check it out.

© Copyright : IT Engg Portal – www.itportal.in 150

What are four types of JDBC driver? Type 1 Drivers

Bridge drivers such as the jdbc-odbc bridge. They rely on an intermediary such as

ODBC to transfer the SQL calls to the database and also often rely on native code. It is

not a serious solution for an application

Type 2 Drivers

Use the existing database API to communicate with the database on the client. Faster

than Type 1, but need native code and require additional permissions to work in an

applet. Client machine requires software to run.

Type 3 Drivers

JDBC-Net pure Java driver. It translates JDBC calls to a DBMS-independent network

protocol, which is then translated to a DBMS protocol by a server. Flexible. Pure Java

and no native code.

Type 4 Drivers

Native-protocol pure Java driver. It converts JDBC calls directly into the network

protocol used by DBMSs. This allows a direct call from the client machine to the

DBMS server. It doesn't need any special native code on the client machine.

Recommended by Sun's tutorial, driver type 1 and 2 are interim solutions where direct

pure Java drivers are not yet available. Driver type 3 and 4 are the preferred way to

access databases using the JDBC API, because they offer all the advantages of Java

technology, including automatic installation. For more info, visit Sun JDBC page

Which type of JDBC driver is the fastest one? JDBC Net pure Java driver(Type IV) is the fastest driver because it converts the jdbc

calls into vendor specific protocol calls and it directly interacts with the database.

Are all the required JDBC drivers to establish connectivity to my database part

of the JDK? No. There aren't any JDBC technology-enabled drivers bundled with the JDK 1.1.x or

Java 2 Platform releases other than the JDBC-ODBC Bridge. So, developers need to

get a driver and install it before they can connect to a database. We are considering

bundling JDBC technology- enabled drivers in the future.

© Copyright : IT Engg Portal – www.itportal.in 151

Is the JDBC-ODBC Bridge multi-threaded? No. The JDBC-ODBC Bridge does not support concurrent access from different

threads. The JDBC-ODBC Bridge uses synchronized methods to serialize all of the

calls that it makes to ODBC. Multi-threaded Java programs may use the Bridge, but

they won't get the advantages of multi-threading. In addition, deadlocks can occur

between locks held in the database and the semaphore used by the Bridge. We are

thinking about removing the synchronized methods in the future. They were added

originally to make things simple for folks writing Java programs that use a single-

threaded ODBC driver.

Does the JDBC-ODBC Bridge support multiple concurrent open statements per

connection?

No. You can open only one Statement object per connection when you are using the

JDBC-ODBC Bridge.

What is the query used to display all tables names in SQL Server (Query

analyzer)? select * from information_schema.tables

Why can't I invoke the ResultSet methods afterLast and beforeFirst when the

method next works? You are probably using a driver implemented for the JDBC 1.0 API. You need to

upgrade to a JDBC 2.0 driver that implements scrollable result sets. Also be sure that

your code has created scrollable result sets and that the DBMS you are using supports

them.

How can I retrieve a String or other object type without creating a new object

each time? Creating and garbage collecting potentially large numbers of objects (millions)

unnecessarily can really hurt performance. It may be better to provide a way to

retrieve data like strings using the JDBC API without always allocating a new object.

We are studying this issue to see if it is an area in which the JDBC API should be

improved. Stay tuned, and please send us any comments you have on this question.

How many types of JDBC Drivers are present and what are they? There are 4 types of JDBC Drivers

Type 1: JDBC-ODBC Bridge Driver

Type 2: Native API Partly Java Driver

© Copyright : IT Engg Portal – www.itportal.in 152

Type 3: Network protocol Driver

Type 4: JDBC Net pure Java Driver

What is the fastest type of JDBC driver? JDBC driver performance will depend on a number of issues:

(a) the quality of the driver code,

(b) the size of the driver code,

(c) the database server and its load,

(d) network topology,

(e) the number of times your request is translated to a different API.

In general, all things being equal, you can assume that the more your request and

response change hands, the slower it will be. This means that Type 1 and Type 3

drivers will be slower than Type 2 drivers (the database calls are make at least three

translations versus two), and Type 4 drivers are the fastest (only one translation).

There is a method getColumnCount in the JDBC API. Is there a similar method

to find the number of rows in a result set? No, but it is easy to find the number of rows. If you are using a scrollable result set, rs,

you can call the methods rs.last and then rs.getRow to find out how many rows rs has.

If the result is not scrollable, you can either count the rows by iterating through the

result set or get the number of rows by submitting a query with a COUNT column in

the SELECT clause.

I would like to download the JDBC-ODBC Bridge for the Java 2 SDK, Standard

Edition (formerly JDK 1.2). I'm a beginner with the JDBC API, and I would like

to start with the Bridge. How do I do it? The JDBC-ODBC Bridge is bundled with the Java 2 SDK, Standard Edition, so there

is no need to download it separately.

If I use the JDBC API, do I have to use ODBC underneath? No, this is just one of many possible solutions. We recommend using a pure Java

JDBC technology-enabled driver, type 3 or 4, in order to get all of the benefits of the

Java programming language and the JDBC API.

© Copyright : IT Engg Portal – www.itportal.in 153

Once I have the Java 2 SDK, Standard Edition, from Sun, what else do I need to

connect to a database? You still need to get and install a JDBC technology-enabled driver that supports the

database that you are using. There are many drivers available from a variety of

sources. You can also try using the JDBC-ODBC Bridge if you have ODBC

connectivity set up already. The Bridge comes with the Java 2 SDK, Standard Edition,

and Enterprise Edition, and it doesn't require any extra setup itself. The Bridge is a

normal ODBC client. Note, however, that you should use the JDBC-ODBC Bridge

only for experimental prototyping or when you have no other driver available.

What is the best way to generate a universally unique object ID? Do I need to use

an external resource like a file or database, or can I do it all in memory? 1: Unique down to the millisecond. Digits 1-8 are the hex encoded lower 32 bits of the

System.currentTimeMillis() call.

2: Unique across a cluster. Digits 9-16 are the encoded representation of the 32 bit

integer of the underlying IP address.

3: Unique down to the object in a JVM. Digits 17-24 are the hex representation of the

call to System.identityHashCode(), which is guaranteed to return distinct integers for

distinct objects within a JVM.

4: Unique within an object within a millisecond. Finally digits 25-32 represent a

random 32 bit integer generated on every method call using the cryptographically

strong java.security.SecureRandom class.

Answer1 There are two reasons to use the random number instead of incrementing your last. 1.

The number would be predictable and, depending on what this is used for, you could

be opening up a potential security issue. This is why ProcessIDs are randomized on

some OSes (AIX for one). 2. You must synchronize on that counter to guarantee that

your number isn't reused. Your random number generator need not be synchronized,

(though its implementation may be).

Answer2 1) If your using Oracle You can create a sequence ,by which you can generate unique

primary key or universal primary key. 2) you can generate by using random numbers

but you may have to check the range and check for unique id. ie random number

generate 0.0 to 1.0 u may have to make some logic which suits your unique id 3) Set

© Copyright : IT Engg Portal – www.itportal.in 154

the maximum value into an XML file and read that file at the time of loading your

application from xml .

What happens when I close a Connection application obtained from a connection

Pool? How does a connection pool maintain the Connections that I had closed

through the application?

Answer1 It is the magic of polymorphism, and of Java interface vs. implementation types. Two

objects can both be "instanceof" the same interface type, even though they are not of

the same implementation type.

When you call "getConnection()" on a pooled connection cache manager object, you

get a "logical" connection, something which implements the java.sql.Connection

interface.

But it is not the same implementation type as you would get for your Connection, if

you directly called getConnection() from a (non-pooled/non-cached) datasource.

So the "close()" that you invoke on the "logical" Connection is not the same "close()"

method as the one on the actual underlying "physical" connection hidden by the pool

cache manager.

The close() method of the "logical" connection object, while it satisfies the method

signature of close() in the java.sql.Connection interface, does not actually close the

underlying physical connection.

Answer2 Typically a connection pool keeps the active/in-use connections in a hashtable or other

Collection mechanism. I've seen some that use one stack for ready-for-use, one stack

for in-use.

When close() is called, whatever the mechanism for indicating inuse/ready-for-use,

that connection is either returned to the pool for ready-for-use or else physically

closed. Connections pools should have a minimum number of connections open. Any

that are closing where the minimum are already available should be physically closed.

Some connection pools periodically test their connections to see if queries work on the

ready-for-use connections or they may test that on the close() method before returning

to the ready-for-use pool.

How do I insert a .jpg into a mySQL data base? I have tried inserting the file as

byte[], but I recieve an error message stating that the syntax is incorrect.

Binary data is stored and retrieved from the database using

© Copyright : IT Engg Portal – www.itportal.in 155

streams in connection with prepared statements and resultsets.

This minimal application stores an image file in the database,

then it retrieves the binary data from the database and converts

it back to an image.

import java.sql.*;

import java.io.*;

import java.awt.*;

import java.awt.Image;

/**

* Storing and retrieving images from a MySQL database

*/

public class StoreBinary {

private static String driverName = "sun.jdbc.odbc.JdbcOdbcDriver";

private Statement stmt = null;

private Connection conn = null;

public StoreBinary() {}

/**

* Strips path prefix from filenames

* @param fileName

* @return the base filename

*/

public static String getBaseName(String fileName) {

int ix=fileName.lastIndexOf("\\");

if (ix < 0) return fileName;

return fileName.substring(ix+1);

}

/**

* Store a binary (image) file in the database using a

* prepared statement.

* @param fileName

* @return true if the operation succeeds

* @throws Exception

*/

public boolean storeImageFile(String fileName) throws Exception {

© Copyright : IT Engg Portal – www.itportal.in 156

if (!connect("test", "root", "")) {

return false;

}

FileInputStream in = new FileInputStream(fileName);

int len=in.available();

String baseName=StoreBinary.getBaseName(fileName);

PreparedStatement pStmt = conn.prepareStatement

("insert into image_tab values (?,?,?)");

pStmt.setString(1, baseName);

pStmt.setInt(2,len);

pStmt.setBinaryStream(3, in, len);

pStmt.executeUpdate();

in.close();

System.out.println("Stored: "+baseName+", length: "+len);

return true;

}

/**

* Retrieve the biary file data from the DB and convert it to an image

* @param fileName

* @return

* @throws Exception

*/

public Image getImageFile(String fileName) throws Exception {

String baseName=StoreBinary.getBaseName(fileName);

ResultSet rs=stmt.executeQuery("select * from image_tab

where image_name='"+baseName+"'");

if (!rs.next()) {

System.out.println("Image:"+baseName+" not found");

return null;

}

int len=rs.getInt(2);

byte [] b=new byte[len];

InputStream in = rs.getBinaryStream(3);

© Copyright : IT Engg Portal – www.itportal.in 157

int n=in.read(b);

System.out.println("n: "+n);

in.close();

Image img=Toolkit.getDefaultToolkit().createImage(b);

System.out.println("Image: "+baseName+" retrieved ok, size: "+len);

return img;

}

/**

* Establish database connection

* @param dbName

* @param dbUser

* @param dbPassword

* @return true if the operation succeeds

*/

public boolean connect(String dbName, String dbUser, String dbPassword) {

try {

Class.forName(driverName);

}

catch (ClassNotFoundException ex) {

ex.printStackTrace();

return false;

}

try {

conn = DriverManager.getConnection("jdbc:odbc:" + dbName,

dbUser,

dbPassword);

stmt = conn.createStatement();

}

catch (SQLException ex1) {

ex1.printStackTrace();

return false;

}

return true;

}

/******************************************

* MAIN stub driver for testing the class.

© Copyright : IT Engg Portal – www.itportal.in 158

*/

public static void main(String[] args) {

String fileName="c:\\tmp\\f128.jpg";

StoreBinary sb = new StoreBinary();

try {

if (sb.storeImageFile(fileName)) {

// stored ok, now get it back again

Image img=sb.getImageFile(fileName);

}

}

catch (Exception ex) {

ex.printStackTrace();

}

}

}

How can I know when I reach the last record in a table, since JDBC doesn't

provide an EOF method? Answer1

You can use last() method of java.sql.ResultSet, if you make it scrollable.

You can also use isLast() as you are reading the ResultSet.

One thing to keep in mind, though, is that both methods tell you that you have reached

the end of the current ResultSet, not necessarily the end of the table. SQL and

RDBMSes make no guarantees about the order of rows, even from sequential

SELECTs, unless you specifically use ORDER BY. Even then, that doesn't necessarily

tell you the order of data in the table.

Answer2

Assuming you mean ResultSet instead of Table, the usual idiom for iterating over a

forward only resultset is:

ResultSet rs=statement.executeQuery(...);

while (rs.next()) {

// Manipulate row here

}

Where can I find info, frameworks and example source for writing a JDBC

driver?

© Copyright : IT Engg Portal – www.itportal.in 159

There a several drivers with source available, like MM.MySQL, SimpleText Database,

FreeTDS, and RmiJdbc. There is at least one free framework, the jxDBCon-Open

Source JDBC driver framework. Any driver writer should also review For Driver

Writers.

How can I create a custom RowSetMetaData object from scratch? One unfortunate aspect of RowSetMetaData for custom versions is that it is an

interface. This means that implementations almost have to be proprietary. The JDBC

RowSet package is the most commonly available and offers the

sun.jdbc.rowset.RowSetMetaDataImpl class. After instantiation, any of the

RowSetMetaData setter methods may be used. The bare minimum needed for a

RowSet to function is to set the Column Count for a row and the Column Types for

each column in the row. For a working code example that includes a custom

RowSetMetaData,

How does a custom RowSetReader get called from a CachedRowSet?

The Reader must be registered with the CachedRowSet using

CachedRowSet.setReader(javax.sql.RowSetReader reader). Once that is done, a call to

CachedRowSet.execute() will, among other things, invoke the readData method.

How do I implement a RowSetReader? I want to populate a CachedRowSet

myself and the documents specify that a RowSetReader should be used. The

single method accepts a RowSetInternal caller and returns void. What can I do in

the readData method? "It can be implemented in a wide variety of ways..." and is pretty vague about what

can actually be done. In general, readData() would obtain or create the data to be

loaded, then use CachedRowSet methods to do the actual loading. This would usually

mean inserting rows, so the code would move to the insert row, set the column data

and insert rows. Then the cursor must be set to to the appropriate position.

How can I instantiate and load a new CachedRowSet object from a non-JDBC

source? The basics are:

* Create an object that implements javax.sql.RowSetReader, which loads the data.

* Instantiate a CachedRowset object.

* Set the CachedRowset's reader to the reader object previously created.

* Invoke CachedRowset.execute().

© Copyright : IT Engg Portal – www.itportal.in 160

Note that a RowSetMetaData object must be created, set up with a description of the

data, and attached to the CachedRowset before loading the actual data.

The following code works with the Early Access JDBC RowSet download available

from the Java Developer Connection and is an expansion of one of the examples:

// Independent data source CachedRowSet Example

import java.sql.*;

import javax.sql.*;

import sun.jdbc.rowset.*;

public class RowSetEx1 implements RowSetReader

{

CachedRowSet crs;

int iCol2;

RowSetMetaDataImpl rsmdi;

String sCol1,

sCol3;

public RowSetEx1()

{

try

{

crs = new CachedRowSet();

crs.setReader(this);

crs.execute(); // load from reader

System.out.println(

"Fetching from RowSet...");

while(crs.next())

{

showTheData();

} // end while next

if(crs.isAfterLast() == true)

{

System.out.println(

© Copyright : IT Engg Portal – www.itportal.in 161

"We have reached the end");

System.out.println("crs row: " +

crs.getRow());

}

System.out.println(

"And now backwards...");

while(crs.previous())

{

showTheData();

} // end while previous

if(crs.isBeforeFirst() == true)

{ System.out.println(

"We have reached the start");

}

crs.first();

if(crs.isFirst() == true)

{ System.out.println(

"We have moved to first");

}

System.out.println("crs row: " +

crs.getRow());

if(crs.isBeforeFirst() == false)

{ System.out.println(

"We aren't before the first row."); }

crs.last();

if(crs.isLast() == true)

{ System.out.println(

"...and now we have moved to the last");

}

© Copyright : IT Engg Portal – www.itportal.in 162

System.out.println("crs row: " +

crs.getRow());

if(crs.isAfterLast() == false)

{

System.out.println(

"we aren't after the last.");

}

} // end try

catch (SQLException ex)

{

System.err.println("SQLException: " +

ex.getMessage());

}

} // end constructor

public void showTheData() throws SQLException

{

sCol1 = crs.getString(1);

if(crs.wasNull() == false)

{ System.out.println("sCol1: " + sCol1); }

else { System.out.println("sCol1 is null"); }

iCol2 = crs.getInt(2);

if (crs.wasNull() == false)

{ System.out.println("iCol2: " + iCol2); }

else { System.out.println("iCol2 is null"); }

sCol3 = crs.getString(3);

if (crs.wasNull() == false)

{

System.out.println("sCol3: " +

sCol3 + "\n" );

© Copyright : IT Engg Portal – www.itportal.in 163

}

else

{ System.out.println("sCol3 is null\n"); }

} // end showTheData

// RowSetReader implementation

public void readData(RowSetInternal caller)

throws SQLException

{

rsmdi = new RowSetMetaDataImpl();

rsmdi.setColumnCount(3);

rsmdi.setColumnType(1, Types.VARCHAR);

rsmdi.setColumnType(2, Types.INTEGER);

rsmdi.setColumnType(3, Types.VARCHAR);

crs.setMetaData( rsmdi );

crs.moveToInsertRow();

crs.updateString( 1, "StringCol11" );

crs.updateInt( 2, 1 );

crs.updateString( 3, "StringCol31" );

crs.insertRow();

crs.updateString( 1, "StringCol12" );

crs.updateInt( 2, 2 );

crs.updateString( 3, "StringCol32" );

crs.insertRow();

crs.moveToCurrentRow();

crs.beforeFirst();

} // end readData

© Copyright : IT Engg Portal – www.itportal.in 164

public static void main(String args[])

{

new RowSetEx1();

}

} // end class RowSetEx1

Can I set up a connection pool with multiple user IDs? The single ID we are

forced to use causes problems when debugging the DBMS.

Since the Connection interface ( and the underlying DBMS ) requires a specific user

and password, there's not much of a way around this in a pool. While you could create

a different Connection for each user, most of the rationale for a pool would then be

gone. Debugging is only one of several issues that arise when using pools.

However, for debugging, at least a couple of other methods come to mind. One is to

log executed statements and times, which should allow you to backtrack to the user.

Another method that also maintains a trail of modifications is to include user and

timestamp as standard columns in your tables. In this last case, you would collect a

separate user value in your program.

How can I protect my database password ? I'm writing a client-side java

application that will access a database over the internet. I have concerns about

the security of the database passwords. The client will have access in one way or

another to the class files, where the connection string to the database, including

user and password, is stored in as plain text. What can I do to protect my

passwords? This is a very common question.

Conclusion: JAD decompiles things easily and obfuscation would not help you. But

you'd have the same problem with C/C++ because the connect string would still be

visible in the executable.

SSL JDBC network drivers fix the password sniffing problem (in MySQL 4.0), but not

the decompile problem. If you have a servlet container on the web server, I would go

that route (see other discussion above) then you could at least keep people from

reading/destroying your mysql database.

Make sure you use database security to limit that app user to the minimum tables that

they need, then at least hackers will not be able to reconfigure your DBMS engine.

Aside from encryption issues over the internet, it seems to me that it is bad practice to

© Copyright : IT Engg Portal – www.itportal.in 165

embed user ID and password into program code. One could generally see the text even

without decompilation in almost any language. This would be appropriate only to a

read-only database meant to be open to the world. Normally one would either force the

user to enter the information or keep it in a properties file.

Detecting Duplicate Keys I have a program that inserts rows in a table. My table

has a column 'Name' that has a unique constraint. If the user attempts to insert a

duplicate name into the table, I want to display an error message by processing

the error code from the database. How can I capture this error code in a Java

program? A solution that is perfectly portable to all databases, is to execute a query for checking

if that unique value is present before inserting the row. The big advantage is that you

can handle your error message in a very simple way, and the obvious downside is that

you are going to use more time for inserting the record, but since you're working on a

PK field, performance should not be so bad.

You can also get this information in a portable way, and potentially avoid another

database access, by capturing SQLState messages. Some databases get more specific

than others, but the general code portion is 23 - "Constraint Violations". UDB2, for

example, gives a specific such as 23505, while others will only give 23000.

What driver should I use for scalable Oracle JDBC applications? Sun recommends using the thin ( type 4 ) driver.

* On single processor machines to avoid JNI overhead.

* On multiple processor machines, especially running Solaris, to avoid

synchronization bottlenecks.

Can you scroll a result set returned from a stored procedure? I am returning a

result set from a stored procedure with type SQLRPGLE but once I reach the

end of the result set it does not allow repositioning. Is it possible to scroll this

result set? A CallableStatement is no different than other Statements in regard to whether related

ResultSets are scrollable. You should create the CallableStatement using

Connection.prepareCall(String sql, int resultSetType, int resultSetConcurrency).

How do I write Greek ( or other non-ASCII/8859-1 ) characters to a database? From the standard JDBC perspective, there is no difference between ASCII/8859-1

characters and those above 255 ( hex FF ). The reason for that is that all Java

characters are in Unicode ( unless you perform/request special encoding ). Implicit in

© Copyright : IT Engg Portal – www.itportal.in 166

that statement is the presumption that the data store can handle characters outside the

hex FF range or interprets different character sets appropriately. That means either:

* The OS, application and database use the same code page and character set. For

example, a Greek version of NT with the DBMS set to the default OS encoding.

* The DBMS has I18N support for Greek ( or other language ), regardless of OS

encoding. This has been the most common for production quality databases, although

support varies. Particular DBMSes may allow setting the encoding/code page/CCSID

at the database, table or even column level. There is no particular standard for

provided support or methods of setting the encoding. You have to check the DBMS

documentation and set up the table properly.

* The DBMS has I18N support in the form of Unicode capability. This would handle

any Unicode characters and therefore any language defined in the Unicode standard.

Again, set up is proprietary.

How can I insert images into a Mysql database? This code snippet shows the basics:

File file = new File(fPICTURE);

FileInputStream fis = new FileInputStream(file);

PreparedStatement ps =

ConrsIn.prepareStatement("insert into dbPICTURE values (?,?)");

// ***use as many ??? as you need to insert in the exact order***

ps.setString(1,file.getName());

ps.setBinaryStream(2,fis,(int)file.length());

ps.close();

fis.close();

Is possible to open a connection to a database with exclusive mode with JDBC? I think you mean "lock a table in exclusive mode". You cannot open a connection with

exclusive mode. Depending on your database engine, you can lock tables or rows in

exclusive mode.

In Oracle you would create a statement st and run

st.execute("lock table mytable in exclusive mode");

Then when you are finished with the table, execute the commit to unlock the table.

Mysql, Informix and SQLServer all have a slightly different syntax for this function,

© Copyright : IT Engg Portal – www.itportal.in 167

so you'll have to change it depending on your database. But they can all be done with

execute().

What are the standard isolation levels defined by JDBC? The values are defined in the class java.sql.Connection and are:

* TRANSACTION_NONE

* TRANSACTION_READ_COMMITTED

* TRANSACTION_READ_UNCOMMITTED

* TRANSACTION_REPEATABLE_READ

* TRANSACTION_SERIALIZABLE

Update fails without blank padding. Although a particular row is present in the

database for a given key, executeUpdate() shows 0 rows updated and, in fact, the

table is not updated. If I pad the Key with spaces for the column length (e.g. if the

key column is 20 characters long, and key is msgID, length 6, I pad it with 14

spaces), the update then works!!! Is there any solution to this problem without

padding? In the SQL standard, CHAR is a fixed length data type. In many DBMSes ( but not

all), that means that for a WHERE clause to match, every character must match,

including size and trailing blanks. As Alessandro indicates, defining CHAR columns

to be VARCHAR is the most general answer.

What isolation level is used by the DBMS when inserting, updating and selecting

rows from a database?

The answer depends on both your code and the DBMS. If the program does not

explicitly set the isolation level, the DBMS default is used. You can determine the

default using DatabaseMetaData.getDefaultTransactionIsolation() and the level for the

current Connection with Connection.getTransactionIsolation(). If the default is not

appropriate for your transaction, change it with Connection.setTransactionIsolation(int

level).

How can I determine the isolation levels supported by my DBMS? Use DatabaseMetaData.supportsTransactionIsolationLevel(int level).

Connecting to a database through the Proxy I want to connect to remote database

using a program that is running in the local network behind the proxy. Is that

possible? I assume that your proxy is set to accept http requests only on port 80. If you want to

© Copyright : IT Engg Portal – www.itportal.in 168

have a local class behind the proxy connect to the database for you, then you need a

servlet/JSP to receive an HTTP request and use the local class to connect to the

database and send the response back to the client.

You could also use RMI where your remote computer class that connects to the

database acts as a remote server that talks RMI with the clients. if you implement this,

then you will need to tunnel RMI through HTTP which is not that hard.

In summary, either have a servlet/JSP take HTTP requests, instantiate a class that

handles database connections and send HTTP response back to the client or have the

local class deployed as RMI server and send requests to it using RMI.

How do I receive a ResultSet from a stored procedure? Stored procedures can return a result parameter, which can be a result set. For a

discussion of standard JDBC syntax for dealing with result, IN, IN/OUT and OUT

parameters, see Stored Procedures.

How can I write to the log used by DriverManager and JDBC drivers? The simplest method is to use DriverManager.println(String message), which will

write to the current log.

How can I get or redirect the log used by DriverManager and JDBC drivers?

As of JDBC 2.0, use DriverManager.getLogWriter() and

DriverManager.setLogWriter(PrintWriter out). Prior to JDBC 2.0, the DriverManager

methods getLogStream() and setLogStream(PrintStream out) were used. These are

now deprecated.

What does it mean to "materialize" data? This term generally refers to Array, Blob and Clob data which is referred to in the

database via SQL locators "Materializing" the data means to return the actual data

pointed to by the Locator.

For Arrays, use the various forms of getArray() and getResultSet().

For Blobs, use getBinaryStream() or getBytes(long pos, int length).

For Clobs, use getAsciiStream() or getCharacterStream().

Why do I have to reaccess the database for Array, Blob, and Clob data? Most DBMS vendors have implemented these types via the SQL3 Locator type

Some rationales for using Locators rather than directly returning the data can be seen

© Copyright : IT Engg Portal – www.itportal.in 169

most clearly with the Blob type. By definition, a Blob is an arbitrary set of binary data.

It could be anything; the DBMS has no knowledge of what the data represents. Notice

that this effectively demolishes data independence, because applications must now be

aware of what the Blob data actually represents. Let's assume an employee table that

includes employee images as Blobs.

Say we have an inquiry program that presents multiple employees with department

and identification information. To see all of the data for a specific employee, including

the image, the summary row is selected and another screen appears. It is only at this

pont that the application needs the specific image. It would be very wasteful and time

consuming to bring down an entire employee page of images when only a few would

ever be selected in a given run.

Now assume a general interactive SQL application. A query is issued against the

employee table. Because the image is a Blob, the application has no idea what to do

with the data, so why bring it down, killing performance along the way, in a long

running operation?

Clearly this is not helpful in those applications that need the data everytime, but these

and other considerations have made the most general sense to DBMS vendors.

What is an SQL Locator? A Locator is an SQL3 data type that acts as a logical pointer to data that resides on a

database server. Read "logical pointer" here as an identifier the DBMS can use to

locate and manipulate the data. A Locator allows some manipulation of the data on the

server. While the JDBC specification does not directly address Locators, JDBC drivers

typically use Locators under the covers to handle Array, Blob, and Clob data types.

How do I set properties for a JDBC driver and where are the properties stored? A JDBC driver may accept any number of properties to tune or optimize performance

for the specific driver. There is no standard, other than user and password, for what

these properties should be. Therefore, the developer is dependent on the driver

documentation to automatically pass properties. For a standard dynamic method that

can be used to solicit user input for properties, see What properties should I supply to

a database driver in order to connect to a database?

In addition, a driver may specify its own method of accepting properties. Many do this

via appending the property to the JDBC Database URL. However, a JDBC Compliant

driver should implement the connect(String url, Properties info) method. This is

generally invoked through DriverManager.getConnection(String url, Properties info).

The passed properties are ( probably ) stored in variables in the Driver instance. This,

© Copyright : IT Engg Portal – www.itportal.in 170

again, is up to the driver, but unless there is some sort of driver setup, which is

unusual, only default values are remembered over multiple instantiations.

What is the JDBC syntax for using a literal or variable in a standard Statement? First, it should be pointed out that PreparedStatement handles many issues for the

developer and normally should be preferred over a standard Statement.

Otherwise, the JDBC syntax is really the same as SQL syntax. One problem that often

affects newbies ( and others ) is that SQL, like many languages, requires quotes

around character ( read "String" for Java ) values to distinguish from numerics. So the

clause:

"WHERE myCol = " + myVal

is perfectly valid and works for numerics, but will fail when myVal is a String. Instead

use:

"WHERE myCol = '" + myVal + "'"

if myVal equals "stringValue", the clause works out to:

WHERE myCol = 'stringValue'

You can still encounter problems when quotes are embedded in the value, which,

again, a PreparedStatement will handle for you.

How do I check in my code whether a maximum limit of database connections

have been reached? Use DatabaseMetaData.getMaxConnections() and compare to the number of

connections currently open. Note that a return value of zero can mean unlimited or,

unfortunately, unknown. Of course, driverManager.getConnection() will throw an

exception if a Connection can not be obtained.

Why do I get UnsatisfiedLinkError when I try to use my JDBC driver? The first thing is to be sure that this does not occur when running non-JDBC apps. If

so, there is a faulty JDK/JRE installation. If it happens only when using JDBC, then

it's time to check the documentation that came with the driver or the driver/DBMS

support. JDBC driver types 1 through 3 have some native code aspect and typically

require some sort of client install. Along with the install, various environment

variables and path or classpath settings must be in place. Because the requirements and

installation procedures vary with the provider, there is no reasonable way to provide

details here. A type 4 driver, on the other hand, is pure Java and should never exhibit

this problem. The trade off is that a type 4 driver is usually slower.

© Copyright : IT Engg Portal – www.itportal.in 171

Many connections from an Oracle8i pooled connection returns statement closed.

I am using import oracle.jdbc.pool.* with thin driver. If I test with many

simultaneous connections, I get an SQLException that the statement is closed.

ere is an example of concurrent operation of pooled connections from the

OracleConnectionPoolDataSource. There is an executable for kicking off threads, a

DataSource, and the workerThread.

The Executable Member

package package6;

/**

* package6.executableTester

*

*/

public class executableTester {

protected static myConnectionPoolDataSource dataSource = null;

static int i = 0;

/**

* Constructor

*/

public executableTester() throws java.sql.SQLException

{

}

/**

* main

* @param args

*/

public static void main(String[] args) {

try{

dataSource = new myConnectionPoolDataSource();

}

catch ( Exception ex ){

ex.printStackTrace();

© Copyright : IT Engg Portal – www.itportal.in 172

}

while ( i++ < 10 ) {

try{

workerClass worker = new workerClass();

worker.setThreadNumber( i );

worker.setConnectionPoolDataSource

( dataSource.getConnectionPoolDataSource() );

worker.start();

System.out.println( "Started Thread#"+i );

}

catch ( Exception ex ){

ex.printStackTrace();

}

}

}

}

The DataSource Member

package package6;

import oracle.jdbc.pool.*;

/**

* package6.myConnectionPoolDataSource.

*

*/

public class myConnectionPoolDataSource extends Object {

protected OracleConnectionPoolDataSource ocpds = null;

/**

* Constructor

*/

public myConnectionPoolDataSource()

throws java.sql.SQLException {

// Create a OracleConnectionPoolDataSource instance

© Copyright : IT Engg Portal – www.itportal.in 173

ocpds = new OracleConnectionPoolDataSource();

// Set connection parameters

ocpds.setURL("jdbc:oracle:oci8:@mydb");

ocpds.setUser("scott");

ocpds.setPassword("tiger");

}

public OracleConnectionPoolDataSource

getConnectionPoolDataSource() {

return ocpds;

}

}

The Worker Thread Member

package package6;

import oracle.jdbc.pool.*;

import java.sql.*;

import javax.sql.*;

/**

* package6.workerClass .

*

*/

public class workerClass extends Thread {

protected OracleConnectionPoolDataSource ocpds = null;

protected PooledConnection pc = null;

protected Connection conn = null;

protected int threadNumber = 0;

/**

* Constructor

*/

© Copyright : IT Engg Portal – www.itportal.in 174

public workerClass() {

}

public void doWork( ) throws SQLException {

// Create a pooled connection

pc = ocpds.getPooledConnection();

// Get a Logical connection

conn = pc.getConnection();

// Create a Statement

Statement stmt = conn.createStatement ();

// Select the ENAME column from the EMP table

ResultSet rset = stmt.executeQuery ("select ename from emp");

// Iterate through the result and print the employee names

while (rset.next ())

// System.out.println (rset.getString (1));

;

// Close the RseultSet

rset.close();

rset = null;

// Close the Statement

stmt.close();

stmt = null;

// Close the logical connection

conn.close();

conn = null;

// Close the pooled connection

pc.close();

© Copyright : IT Engg Portal – www.itportal.in 175

pc = null;

System.out.println( "workerClass.thread#

"+threadNumber+" completed..");

}

public void setThreadNumber( int assignment ){

threadNumber = assignment;

}

public void setConnectionPoolDataSource

(OracleConnectionPoolDataSource x){

ocpds = x;

}

public void run() {

try{

doWork();

}

catch ( Exception ex ){

ex.printStackTrace();

}

}

}

The OutPut Produced

Started Thread#1

Started Thread#2

Started Thread#3

Started Thread#4

Started Thread#5

Started Thread#6

Started Thread#7

Started Thread#8

© Copyright : IT Engg Portal – www.itportal.in 176

Started Thread#9

Started Thread#10

workerClass.thread# 1 completed..

workerClass.thread# 10 completed..

workerClass.thread# 3 completed..

workerClass.thread# 8 completed..

workerClass.thread# 2 completed..

workerClass.thread# 9 completed..

workerClass.thread# 5 completed..

workerClass.thread# 7 completed..

workerClass.thread# 6 completed..

workerClass.thread# 4 completed..

The oracle.jdbc.pool.OracleConnectionCacheImpl class is another subclass of the

oracle.jdbc.pool.OracleDataSource which should also be looked over, that is what you

really what to use. Here is a similar example that uses the

oracle.jdbc.pool.OracleConnectionCacheImpl. The general construct is the same as the

first example but note the differences in workerClass1 where some statements have

been commented ( basically a clone of workerClass from previous example ).

The Executable Member

package package6;

import java.sql.*;

import javax.sql.*;

import oracle.jdbc.pool.*;

/**

* package6.executableTester2

*

*/

public class executableTester2 {

static int i = 0;

protected static myOracleConnectCache

connectionCache = null;

/**

* Constructor

© Copyright : IT Engg Portal – www.itportal.in 177

*/

public executableTester2() throws SQLException

{

}

/**

* main

* @param args

*/

public static void main(String[] args) {

OracleConnectionPoolDataSource dataSource = null;

try{

dataSource = new OracleConnectionPoolDataSource() ;

connectionCache = new myOracleConnectCache( dataSource );

}

catch ( Exception ex ){

ex.printStackTrace();

}

while ( i++ < 10 ) {

try{

workerClass1 worker = new workerClass1();

worker.setThreadNumber( i );

worker.setConnection( connectionCache.getConnection() );

worker.start();

System.out.println( "Started Thread#"+i );

}

catch ( Exception ex ){

ex.printStackTrace();

}

}

}

protected void finalize(){

try{

© Copyright : IT Engg Portal – www.itportal.in 178

connectionCache.close();

} catch ( SQLException x) {

x.printStackTrace();

}

this.finalize();

}

}

The ConnectCacheImpl Member

package package6;

import javax.sql.ConnectionPoolDataSource;

import oracle.jdbc.pool.*;

import oracle.jdbc.driver.*;

import java.sql.*;

import java.sql.SQLException;

/**

* package6.myOracleConnectCache

*

*/

public class myOracleConnectCache extends

OracleConnectionCacheImpl {

/**

* Constructor

*/

public myOracleConnectCache( ConnectionPoolDataSource x)

throws SQLException {

initialize();

}

public void initialize() throws SQLException {

setURL("jdbc:oracle:oci8:@myDB");

setUser("scott");

setPassword("tiger");

© Copyright : IT Engg Portal – www.itportal.in 179

//

// prefab 2 connection and only grow to 4 , setting these

// to various values will demo the behavior

//clearly, if it is not

// obvious already

//

setMinLimit(2);

setMaxLimit(4);

}

}

The Worker Thread Member

package package6;

import oracle.jdbc.pool.*;

import java.sql.*;

import javax.sql.*;

/**

* package6.workerClass1

*

*/

public class workerClass1 extends Thread {

// protected OracleConnectionPoolDataSource

ocpds = null;

// protected PooledConnection pc = null;

protected Connection conn = null;

protected int threadNumber = 0;

/**

* Constructor

*/

public workerClass1() {

© Copyright : IT Engg Portal – www.itportal.in 180

}

public void doWork( ) throws SQLException {

// Create a pooled connection

// pc = ocpds.getPooledConnection();

// Get a Logical connection

// conn = pc.getConnection();

// Create a Statement

Statement stmt = conn.createStatement ();

// Select the ENAME column from the EMP table

ResultSet rset = stmt.executeQuery

("select ename from EMP");

// Iterate through the result

// and print the employee names

while (rset.next ())

// System.out.println (rset.getString (1));

;

// Close the RseultSet

rset.close();

rset = null;

// Close the Statement

stmt.close();

stmt = null;

// Close the logical connection

conn.close();

conn = null;

// Close the pooled connection

// pc.close();

© Copyright : IT Engg Portal – www.itportal.in 181

// pc = null;

System.out.println( "workerClass1.thread#

"+threadNumber+" completed..");

}

public void setThreadNumber( int assignment ){

threadNumber = assignment;

}

// public void setConnectionPoolDataSource

(OracleConnectionPoolDataSource x){

// ocpds = x;

// }

public void setConnection( Connection assignment ){

conn = assignment;

}

public void run() {

try{

doWork();

}

catch ( Exception ex ){

ex.printStackTrace();

}

}

}

The OutPut Produced

Started Thread#1

Started Thread#2

workerClass1.thread# 1 completed..

workerClass1.thread# 2 completed..

© Copyright : IT Engg Portal – www.itportal.in 182

Started Thread#3

Started Thread#4

Started Thread#5

workerClass1.thread# 5 completed..

workerClass1.thread# 4 completed..

workerClass1.thread# 3 completed..

Started Thread#6

Started Thread#7

Started Thread#8

Started Thread#9

workerClass1.thread# 8 completed..

workerClass1.thread# 9 completed..

workerClass1.thread# 6 completed..

workerClass1.thread# 7 completed..

Started Thread#10

workerClass1.thread# 10 completed.. DB2 Universal claims to support JDBC 2.0,

But I can only get JDBC 1.0 functionality. What can I do?

DB2 Universal defaults to the 1.0 driver. You have to run a special program to enable

the 2.0 driver and JDK support. For detailed information, see Setting the Environment

in Building Java Applets and Applications. The page includes instructions for most

supported platforms.

How do I disallow NULL values in a table? Null capability is a column integrity constraint, normally applied at table creation

time. Note that some databases won't allow the constraint to be applied after table

creation. Most databases allow a default value for the column as well. The following

SQL statement displays the NOT NULL constraint:

CREATE TABLE CoffeeTable (

Type VARCHAR(25) NOT NULL,

Pounds INTEGER NOT NULL,

Price NUMERIC(5, 2) NOT NULL

)

How to get a field's value with ResultSet.getxxx when it is a NULL? I have tried

to execute a typical SQL statement:

select * from T-name where (clause);

© Copyright : IT Engg Portal – www.itportal.in 183

But an error gets thrown because there are some NULL fields in the table. You should not get an error/exception just because of null values in various columns.

This sounds like a driver specific problem and you should first check the original and

any chained exceptions to determine if another problem exists. In general, one may

retrieve one of three values for a column that is null, depending on the data type. For

methods that return objects, null will be returned; for numeric ( get Byte(), getShort(),

getInt(), getLong(), getFloat(), and getDouble() ) zero will be returned; for

getBoolean() false will be returned. To find out if the value was actually NULL, use

ResultSet.wasNull() before invoking another getXXX method.

How do I insert/update records with some of the columns having NULL value? Use either of the following PreparedStatement methods:

public void setNull(int parameterIndex, int sqlType) throws SQLException

public void setNull(int paramIndex, int sqlType, String typeName) throws

SQLException

These methods assume that the columns are nullable. In this case, you can also just

omit the columns in an INSERT statement; they will be automatically assigned null

values.

Is there a way to find the primary key(s) for an Access Database table? Sun's

JDBC-ODBC driver does not implement the getPrimaryKeys() method for the

DatabaseMetaData Objects. // Use meta.getIndexInfo() will

//get you the PK index. Once

// you know the index, retrieve its column name

DatabaseMetaData meta = con.getMetaData();

String key_colname = null;

// get the primary key information

rset = meta.getIndexInfo(null,null, table_name, true,true);

while( rset.next())

{

String idx = rset.getString(6);

if( idx != null)

{

© Copyright : IT Engg Portal – www.itportal.in 184

//Note: index "PrimaryKey" is Access DB specific

// other db server has diff. index syntax.

if( idx.equalsIgnoreCase("PrimaryKey"))

{

key_colname = rset.getString(9);

setPrimaryKey( key_colname );

}

}

}

Why can't Tomcat find my Oracle JDBC drivers in classes111.zip? TOMCAT 4.0.1 on NT4 throws the following exception when I try to connect to

Oracle DB from JSP.

javax.servlet.ServletException : oracle.jdbc.driver.OracleDriver

java.lang.ClassNotFoundException: oracle:jdbc:driver:OracleDriver

But, the Oracle JDBC driver ZIP file (classes111.zip)is available in the system

classpath.

Copied the Oracle Driver class file (classes111.zip) in %TOMCAT_Home -

Home%\lib directory and renamed it to classess111.jar.

Able to connect to Oracle DB from TOMCAT 4.01 via Oracle JDBC-Thin Driver.

I have an application that queries a database and retrieves the results into a

JTable. This is the code in the model that seems to be taken forever to execute,

especially for a large result set:

while ( myRs.next() ) {

Vector newRow =new Vector();

for ( int i=1;i<=numOfCols;i++ )

{

newRow.addElement(myRs.getObject(i));

}

allRows.addElement(newRow);

}

fireTableChanged(null);

newRow stores each row of the resultset and allRows stores all the rows.

Are the vectors here the problem?

© Copyright : IT Engg Portal – www.itportal.in 185

Is there another way of dealing with the result set that could execute faster? java.util.Vector is largely thread safe, which means that there is a greater overhead in

calling addElement() as it is a synchronized method. If your result set is very large,

and threading is not an issue, you could use one of the thread-unsafe collections in

Java 2 to save some time. java.util.ArrayList is the likeliest candidate here.

Do not use a DefaultTableModel as it loads all of your data into memory at once,

which will obviously cause a large overhead - instead, use an AbstractTableModel and

provide an implementation which only loads data on demand, i.e. when (if) the user

scrolls down through the table.

How does one get column names for rows returned in a ResultSet? ResultSet rs = ...

...

ResultSetMetaData rsmd = rs.getMetaData();

int numCols = rsmd.getColumnCount();

for (int i = 1; i <= numCols; i++)

{

System.out.println("[" + i + "]" +

rsmd.getColumnName(i) + " {" +

rsmd.getColumnTypeName(i) + "}");

}

What are the considerations for deciding on transaction boundaries? Transaction processing should always deal with more than one statement and a

transaction is often described as a Logical Unit of Work ( LUW ). The rationale for

transactions is that you want to know definitively that all or none of the LUW

completed successfully. Note that this automatically gives you restart capability.

Typically, there are two conditions under which you would want to use transactions:

* Multiple statements involving a single file - An example would be inserting all of a

group of rows or all price updates for a given date. You want all of these to take effect

at the same time; inserting or changing some subset is not acceptable.

* Multiple statements involving multiple files - The classic example is transferring

money from one account to another or double entry accounting; you don't want the

debit to succeed and the credit to fail because money or important records will be lost.

Another example is a master/detail relationship, where, say, the master contains a total

column. If the entire LUW, writing the detail row and updating the master row, is not

© Copyright : IT Engg Portal – www.itportal.in 186

completed successfully, you A) want to know that the transaction was unsuccessful

and B) that a portion of the transaction was not lost or dangling.

Therefore, determining what completes the transaction or LUW should be the deciding

factor for transaction boundaries.

How can I determine where a given table is referenced via foreign keys?

DatabaseMetaData.getExportedKeys() returns a ResultSet with data similar to that

returned by DatabaseMetaData.getImportedKeys(), except that the information relates

to other tables that reference the given table as a foreign key container.

How can I get information about foreign keys used in a table? DatabaseMetaData.getImportedKeys() returns a ResultSet with data about foreign key

columns, tables, sequence and update and delete rules.

Can I use JDBC to execute non-standard features that my DBMS provides? The answer is a qualified yes. As discussed under SQL Conformance: "One way the

JDBC API deals with this problem is to allow any query string to be passed through to

an underlying DBMS driver. This means that an application is free to use as much

SQL functionality as desired, but it runs the risk of receiving an error on some

DBMSs. In fact, an application query may be something other than SQL, or it may be

a specialized derivative of SQL designed for specific DBMSs (for document or image

queries, for example)."

Clearly this means either giving up portability or checking the DBMS currently used

before invoking specific operations.

What is DML?

DML is an abbreviation for Data Manipulation Language. This portion of the SQL

standard is concerned with manipulating the data in a database as opposed to the

structure of a database. The core verbs for DML are SELECT, INSERT, DELETE,

UPDATE, COMMIT and ROLLBACK.

What is the significance of DataBaseMetaData.tableIndexStatistics? How to

obtain and use it? To answer the second question first, the tableIndexStatistic constant in the TYPE

column will identify one of the rows in the ResultSet returned when

DatabaseMetaData.getIndexInfo() is invoked. If you analyze the wordy API, a

tableIndexStatistic row will contain the number of rows in the table in the

© Copyright : IT Engg Portal – www.itportal.in 187

CARDINALITY column and the number of pages used for the table in the PAGES

column.

What types of DataSource objects are specified in the Optional Package? * Basic - Provides a standard Connection object.

* Pooled - Provides a Connection pool and returns a Connection that is controlled by

the pool.

* Distributed - Provides a Connection that can participate in distributed transactions (

more than one DBMS is involved). It is anticipated, but not enforced, that a distributed

DataSource will also provide pooling.

However, there are no standard methods available in the DataSource class to

determine if one has obtained a pooled and/or distributed Connection.

What is a JDBC 2.0 DataSource? The DataSource class was introduced in the JDBC 2.0 Optional Package as an easier,

more generic means of obtaining a Connection. The actual driver providing services is

defined to the DataSource outside the application ( Of course, a production quality app

can and should provide this information outside the app anyway, usually with

properties files or ResourceBundles ). The documentation expresses the view that

DataSource will replace the common DriverManager method.

Does the database server have to be running Java or have Java support in order

for my remote JDBC client app to access the database? The answer should always be no. The two critical requirements are LAN/internet

connectivity and an appropriate JDBC driver. Connectivity is usually via TCP/IP, but

other communication protocols are possible. Unspoken, but assumed here is that the

DBMS has been started to listen on a communications port. It is the JDBC driver's job

to convert the SQL statements and JDBC calls to the DBMS' native protocol. From the

server's point of view, it's just another data request coming into the port, the

programming language used to send the data is irrelevant at that point.

Which Java and java.sql data types map to my specific database types? JDBC is, of necessity, reliant on the driver and underlying DBMS. These do not

always adhere to standards as closely as we would like, including differing names for

standard Java types. To deal with this, first, there are a number of tables available in

the JDK JDBC documentation dealing with types.

© Copyright : IT Engg Portal – www.itportal.in 188

Are the code examples from the JDBC API Tutorial and Reference, Second

Edition available online? Yes.

When an SQL select statement doesn't return any rows, is an SQLException

thrown? No. If you want to throw an exception, you could wrap your SQL related code in a

custom class and throw something like ObjectNotFoundException when the returned

ResultSet is empty.

Why should I consider optimistic versus pessimistic approaches to database

updates? In a modern database, possibly the two most important issues are data integrity and

concurrency ( multiple users have access to and can update the data ). Either approach

can be appropriate, depending on the application, but it is important to be aware of

possible consequences to avoid being blindsided.

A pessimistic approach, with locks, is usually seen as good for data integrity, although

it can be bad for concurrency, especially the longer a lock is held. In particular, it

guarantees against 'lost updates' - defined as an update performed by one process

between the time of access and update by another process, which overwrites the

interim update. However, other users are blocked from updating the data and possibly

reading it as well if the read access also tries to acquire a lock. A notorious problem

can arise when a user accesses data for update and then doesn't act on it for a period of

time. Another situation that occurred with one of my clients is that a batch ( non-

interactive ) process may need to update data while an interactive user has an update

lock on the same data. In that case, data integrity goes out the window and, depending

on how the application is written, more problems may be introduced. ( No, we did not

write the interactive update program and yes, we had recovery procedures in place. )

An optimstic approach can alleviate lock concurrency problems, but requires more

code and care for integrity. The "optimistic" definition usually says that expectations

of update clashes are rare, but I view them as normal occurrances in a heavily used

database. The basics are that any changes between time of access and time of update

must be detected and taken into account. This is often done by comparing timestamps,

but one must be sure that the timestamp is always changed for an update and, of

course, that the table contains a timestamp column. A more involved, but more

complete method involves saving the original columns and using them in the 'Where'

© Copyright : IT Engg Portal – www.itportal.in 189

clause of the Update statement. If the update fails, the data has changed and the latest

data should be reaccessed.

What is optimistic concurrency? An optimistic approach dispenses with locks ( except during the actual update ) and

usually involves comparison of timestamps, or generations of data to ensure that data

hasn't changed between access and update times. It's generally explained that the term

optimistic is used because the expectation is that a clash between multiple updates to

the same data will seldom occur.

What is pessimistic concurrency? With a pessimistic approach, locks are used to ensure that no users, other than the one

who holds the lock, can update data. It's generally explained that the term pessimistic

is used because the expectation is that many users will try to update the same data, so

one is pessimistic that an update will be able to complete properly. Locks may be

acquired, depending on the DBMS vendor, automatically via the selected Isolation

Level. Some vendors also implement 'Select... for Update', which explicitly acquires a

lock.

Can I get information about a ResultSet's associated Statement and Connection

in a method without having or adding specific arguments for the Statement and

Connection? Yes. Use ResultSet.getStatement(). From the resulting Statement you can use

Statement.getConnection().

How can I tell if my JDBC driver normalizes java.sql.Date and java.sql.Time

objects? To actually determine the values, the objects must be converted to a java.util.Date and

examined. See What does normalization mean for java.sql.Date and java.sql.Time? for

the definition of normalization. Notice that even a debugger will not show whether

these objects have been normalized, since the getXXX methods in java.sql.Date for

time elements and in java.sql.Time for date elements throw an exception.

So, while a java.sql.Date may show 2001-07-26, it's normalized only if the

java.util.Date value is:

Thu Jul 26 00:00:00 EDT 2001

and while a java.sql.Time may show 14:01:00, it's normalized only if the java.util.Date

value is:

Thu Jan 01 14:01:00 EST 1970

© Copyright : IT Engg Portal – www.itportal.in 190

What is the most efficient method of replicating data between databases using

JDBC?

Within Java, the most efficient method would be, opening connections using the JDBC

and inserting or updating the records from one database to the other database, but it

depends upon the databases being replicated. If you are using Oracle databases, it has

standard methods for replication, and you do not need the JDBC for the replication.

Use snapshots like updateable and read-only.

There are different kind of replication. Let us consider the most widely used ones:

A) One Master - One slave

I) If there is not a significant difference between the structure of the database tables,

the following method would be useful.

FromDatabase=A; ToDatabase=B

1) Open JDBC connections between the databases A and B.

2) Read a record (RA ) from A using an SQL query.

3) Store the values in the local variables in the Java program.

4) Insert the record in B if PK does not exist for the record RA in B.

5) If the PK exists in B, update the record in B.

6) Repeat the steps 2-5 'til all the records are read by the query.

7) If there are multiple tables to be replicated, repeat steps 2-7 using the different

queries.

II)If there is significant difference between the structure of the database tables, the

following method would be useful.

FromDatabase=A; ToDatabase=B

1) Open the JDBC connections to the databases A.

2) Read a record ( RA ) from A using an SQL query.

3) Write the output to an XML file-XMLA, according to the DTD for the records for

the database A structure.

4) Repeat steps 2 & 3 'til all the records are written to XMLA.

5) If there are more queries, repeat steps repeat steps from 2-4 and write the records to

the different entities in the XML file.

6) Transform the XMLA file using the XSL and XSLT to the format useful for the

database B and write to the XML file-XMLB.

7) Open the second JDBC connection to the Database B.

8) Read the XMLB file, one record at a time.

9) Insert the record in B if PK does not exist for the record RA in B.

10) If the PK exists in B, update the record in B.

© Copyright : IT Engg Portal – www.itportal.in 191

B) One Master - Multiple slaves

The difference here is to open multiple JDBC connections to write to the different

databases one record at a time.

C) Multiple Masters:

For multiple masters, use timestamps to compare the times of the records to find out

which is the latest record when a record is found in all the master databases.

Alternatively, create a column to store the time and date a record is inserted or

updated. When records are deleted, record the event in a log file along with the PK.

Prepared statements and batch updates should be used wherever possible in this

scenario.

What is the difference between setMaxRows(int) and SetFetchSize(int)? Can

either reduce processing time? setFetchSize(int) defines the number of rows that will be read from the database when

the ResultSet needs more rows. The method in the java.sql.Statement interface will set

the 'default' value for all the ResultSet derived from that Statement; the method in the

java.sql.ResultSet interface will override that value for a specific ResultSet. Since

database fetches can be expensive in a networked environment, fetch size has an

impact on performance.

setMaxRows(int) sets the limit of the maximum nuber of rows in a ResultSet object. If

this limit is exceeded, the excess rows are "silently dropped". That's all the API says,

so the setMaxRows method may not help performance at all other than to decrease

memory usage. A value of 0 (default) means no limit.

Since we're talking about interfaces, be careful because the implementation of drivers

is often different from database to database and, in some cases, may not be

implemented or have a null implementation. Always refer to the driver documentation.

What is JDO? JDO provides for the transparent persistence of data in a data store agnostic manner,

supporting object, hierarchical, as well as relational stores.

When I intersperse table creation or other DDL statements with DML

statements, I have a problem with a transaction being commited before I want it

to be. Everything ( commit and rollback ) works fine as long as I don't create

another table. How can I resolve the issue? While the questioner found a partially workable method for his particular DBMS, as

mentioned in the section on transactions in my JDBC 2.0 Fundamentals Short Course:

© Copyright : IT Engg Portal – www.itportal.in 192

DDL statements in a transaction may be ignored or may cause a commit to occur. The

behavior is DBMS dependent and can be discovered by use of

DatabaseMetaData.dataDefinitionCausesTransactionCommit() and

DatabaseMetaData.dataDefinitionIgnoredInTransactions(). One way to avoid

unexpected results is to separate DML and DDL transactions.

The only generally effective way to "rollback" table creation is to delete the table.

What's the best way, in terms of performance, to do multiple insert/update

statements, a PreparedStatement or Batch Updates? Because PreparedStatement objects are precompiled, their execution can be faster than

that of Statement objects. Consequently, an SQL statement that is executed many

times is often created as a PreparedStatement object to increase efficiency.

A CallableStatement object provides a way to call stored procedures in a standard

manner for all DBMSes. Their execution can be faster than that of PreparedStatement

object.

Batch updates are used when you want to execute multiple statements together.

Actually, there is no conflict here. While it depends on the driver/DBMS engine as to

whether or not you will get an actual performance benefit from batch updates,

Statement, PreparedStatement, and CallableStatement can all execute the addBatch()

method.

I need to have result set on a page where the user can sort on the column headers.

Any ideas? One possibility: Have an optional field in your form or GET url called (appropriately)

ORDER with a default value of either "no order" or whatever you want your default

ordering to be (i.e. timestamp, username, whatever). When you get your request, see

what the value of the ORDER element is. If it's null or blank, use the default. Use that

value to build your SQL query, and display the results to the page. If you're caching

data in your servlet, you can use the Collection framework to sort your data (see

java.util.Collections) if you can get it into a List format. Then, you can create a

Collator which can impose a total ordering on your results.

What are the components of the JDBC URL for Oracle's "thin" driver and how

do I use them? Briefly: jdbc:oracle:thin:@hostname:port:oracle-sid

1. in green the Oracle sub-protocol (can be oracle:oci7:@, oracle:oci8:@,

racle:thin:@, etc...) is related on the driver you are unsign and the protocol to

© Copyright : IT Engg Portal – www.itportal.in 193

communicate with server.

2. in red the network machine name, or its ip address, to locate the server where oracle

is running.

3. in blue the port (it is complementary to the address to select the specific oracle

service)

4. in magenta the sid, select on which database you want to connect.

example:

jdbc:oracle:thin:@MyOracleHost:1521:MyDB

IHere's an example:

jdbc:oracle:thin:scott/tiger@MyOracleHost:1521:MyDB

where user=scott and pass=tiger.

Why doesn't JDBC accept URLs instead of a URL string? In order for something to be a java.net.URL, a protocol handler needs to be installed.

Since there is no one universal protocol for databases behind JDBC, the URLs are

treated as strings. In Java 1.4, these URL strings have a class called java.net.URI.

However, you still can't use a URI to load a JDBC driver, without converting it to a

string.

What JDBC objects generate SQLWarnings? Connections, Statements and ResultSets all have a getWarnings method that allows

retrieval. Keep in mind that prior ResultSet warnings are cleared on each new read and

prior Statement warnings are cleared with each new execution. getWarnings() itself

does not clear existing warnings, but each object has a clearWarnings method.

What's the fastest way to normalize a Time object? Of the two recommended ways when using a Calendar( see How do I create a

java.sql.Time object? ), in my tests, this code ( where c is a Calendar and t is a Time ):

c.set( Calendar.YEAR, 1970 );

c.set( Calendar.MONTH, Calendar.JANUARY );

c.set( Calendar.DATE, 1 );

c.set( Calendar.MILLISECOND, 0 );

t = new java.sql.Time( c.getTime().getTime() );

was always at least twice as fast as:

© Copyright : IT Engg Portal – www.itportal.in 194

t = java.sql.Time.valueOf(

c.get(Calendar.HOUR_OF_DAY) + ":" +

c.get(Calendar.MINUTE) + ":" +

c.get(Calendar.SECOND) );

When the argument sent to valueOf() was hardcoded ( i.e. valueOf( "13:50:10" ), the

time difference over 1000 iterations was negligible.

What does normalization mean for java.sql.Date and java.sql.Time? These classes are thin wrappers extending java.util.Date, which has both date and time

components. java.sql.Date should carry only date information and a normalized

instance has the time information set to zeros. java.sql.Time should carry only time

information and a normalized instance has the date set to the Java epoch ( January 1,

1970 ) and the milliseconds portion set to zero.

How do I create a java.sql.Date object?

java.sql.Date descends from java.util.Date, but uses only the year, month and day

values. There are two methods to create a Date object. The first uses a Calendar object,

setting the year, month and day portions to the desired values. The hour, minute,

second and millisecond values must be set to zero. At that point,

Calendar.getTime().getTime() is invoked to get the java.util.Date milliseconds. That

value is then passed to a java.sql.Date constructor:

Calendar cal = Calendar.getInstance();

// set Date portion to January 1, 1970

cal.set( cal.YEAR, 1970 );

cal.set( cal.MONTH, cal.JANUARY );

cal.set( cal.DATE, 1 );

cal.set( cal.HOUR_OF_DAY, 0 );

cal.set( cal.MINUTE, 0 );

cal.set( cal.SECOND, 0 );

cal.set( cal.MILLISECOND, 0 );

java.sql.Date jsqlD =

new java.sql.Date( cal.getTime().getTime() );

© Copyright : IT Engg Portal – www.itportal.in 195

The second method is java.sql.Date's valueOf method. valueOf() accepts a String,

which must be the date in JDBC time escape format - "yyyy-mm-dd". For example,

java.sql.Date jsqlD = java.sql.Date.valueOf( "2010-01-31" );

creates a Date object representing January 31, 2010. To use this method with a

Calendar object, use:

java.sql.Date jsqlD = java.sql.Date.valueOf(

cal.get(cal.YEAR) + ":" +

cal.get(cal.MONTH) + ":" +

cal.get(cal.DATE) );

which produces a Date object with the same value as the first example.

How do I create a java.sql.Time object? java.sql.Time descends from java.util.Date, but uses only the hour, minute and second

values. There are two methods to create a Time object. The first uses a Calendar

object, setting the year, month and day portions to January 1, 1970, which is Java's

zero epoch. The millisecond value must also be set to zero. At that point,

Calendar.getTime().getTime() is invoked to get the time in milliseconds. That value is

then passed to a Time constructor:

Calendar cal = Calendar.getInstance();

// set Date portion to January 1, 1970

cal.set( cal.YEAR, 1970 );

cal.set( cal.MONTH, cal.JANUARY );

cal.set( cal.DATE, 1 );

cal.set( cal.MILLISECOND, 0 );

java.sql.Time jsqlT =

new java.sql.Time( cal.getTime().getTime() );

The second method is Time's valueOf method. valueOf() accepts a String, which must

be the time in JDBC time escape format - "hh:mm:ss". For example,

java.sql.Time jsqlT = java.sql.Time.valueOf( "18:05:00" );

creates a Time object representing 6:05 p.m. To use this method with a Calendar

© Copyright : IT Engg Portal – www.itportal.in 196

object, use:

java.sql.Time jsqlT = java.sql.Time.valueOf(

cal.get(cal.HOUR_OF_DAY) + ":" +

cal.get(cal.MINUTE) + ":" +

cal.get(cal.SECOND) );

which produces a Time object with the same value as the first example.

What scalar functions can I expect to be supported by JDBC? JDBC supports numeric, string, time, date, system, and conversion functions on scalar

values. For a list of those supported and additional information, see section A.1.4

Support Scalar Functions in the JDBC Data Access API For Driver Writers. Note that

drivers are only expected to support those scalar functions that are supported by the

underlying DB engine.

What does setFetchSize() really do? The API documentation explains it pretty well, but a number of programmers seem to

have a misconception of its functionality. The first thing to note is that it may do

nothing at all; it is only a hint, even to a JDBC Compliant driver. setFetchSize() is

really a request for a certain sized blocking factor, that is, how much data to send at a

time.

Because trips to the server are expensive, sending a larger number of rows can be

more efficient. It may be more efficient on the server side as well, depending on the

particular SQL statement and the DB engine. That would be true if the data could be

read straight off an index and the DB engine paid attention to the fetch size. In that

case, the DB engine could return only enough data per request to match the fetch size.

Don't count on that behavior. In general, the fetch size will be transparent to your

program and only determines how often requests are sent to the server as you traverse

the data.

Also, both Statement and ResultSet have setFetchSize methods. If used with a

Statement, all ResultSets returned by that Statement will have the same fetch size. The

method can be used at any time to change the fetch size for a given ResultSet. To

determine the current or default size, use the getFetchSize methods.

Is there a practical limit for the number of SQL statements that can be added to

an instance of a Statement object While the specification makes no mention of any size limitation for

© Copyright : IT Engg Portal – www.itportal.in 197

Statement.addBatch(), this seems to be dependent, as usual, on the driver. Among

other things, it depends on the type of container/collection used. I know of at least one

driver that uses a Vector and grows as needed. I've seen questions about another driver

that appears to peak somewhere between 500 and 1000 statements. Unfortunately,

there doesn't appear to be any metadata information regarding possible limits. Of

course, in a production quality driver, one would expect an exception from an

addBatch() invocation that went beyond the command list's limits.

How can I determine whether a Statement and its ResultSet will be closed on a

commit or rollback? Use the DatabaseMetaData methods supportsOpenStatementsAcrossCommit() and

supportsOpenStatementsAcrossRollback().

How do I get runtime information about the JDBC Driver? Use the following DatabaseMetaData methods:

getDriverMajorVersion()

getDriverMinorVersion()

getDriverName()

getDriverVersion()

How do I create an updatable ResultSet? Just as is required with a scrollable ResultSet, the Statement must be capable of

returning an updatable ResultSet. This is accomplished by asking the Connection to

return the appropriate type of Statement using Connection.createStatement(int

resultSetType, int resultSetConcurrency). The resultSetConcurrency parameter must

be ResultSet.CONCUR_UPDATABLE. The actual code would look like this:

Statement stmt = con.createStatement( ResultSet.TYPE_SCROLL_SENSITIVE,

ResultSet.CONCUR_UPDATABLE );

Note that the spec allows a driver to return a different type of Statement/ResultSet than

that requested, depending on capabilities and circumstances, so the actual type

returned should be checked with ResultSet.getConcurrency().

How can I connect to an Oracle database not on the web server from an

untrusted applet?

© Copyright : IT Engg Portal – www.itportal.in 198

You can use the thin ORACLE JDBC driver in an applet (with some extra parameters

on the JDBC URL). Then, if you have NET8, you can use the connection manager of

NET8 on the web server to proxy the connection request to the database server.

How can I insert multiple rows into a database in a single transaction? //turn off the implicit commit

Connection.setAutoCommit(false);

//..your insert/update/delete goes here

Connection.Commit();

a new transaction is implicitly started.

JDBC 2.0 provides a set of methods for executing a batch of database commands.

Specifically, the java.sql.Statement interface provides three methods: addBatch(),

clearBatch() and executeBatch(). Their documentation is pretty straight forward.

The implementation of these methods is optional, so be sure that your driver supports

these.

How do I display and parse a date?

The Java I18N way is to use a DateFormat. While SimpleDateFormat, which is

generally returned, creates a large number of objects, it is locale aware and will handle

most of your needs. The following sample code initially creates a java.sql.Date object

and formats it for the default locale. An initial actionPerformed call additionally

formats/displays it for a German locale and also displays the resulting java.sql.Date in

standard escape format. Other dates can be entered and parsed after the initial display.

// JDFDP.java - Display and Parse java.sql.Date

import java.sql.*;

import javax.swing.*;

import java.awt.*;

import java.awt.event.*;

import java.text.*;

import java.util.*;

public class JDFDP extends JFrame

implements ActionListener,

WindowListener

{

© Copyright : IT Engg Portal – www.itportal.in 199

// create a java.sql.Date

java.sql.Date jsqlDate = new java.sql.Date(

System.currentTimeMillis() );

DateFormat dfLocal = DateFormat.getDateInstance(

DateFormat.SHORT );

DateFormat dfGermany = DateFormat.getDateInstance(

DateFormat.SHORT, Locale.GERMANY );

JButton jb = new JButton( "Go" );

JLabel jlI = new JLabel("Input a Date:"),

jlD = new JLabel("Display German:"),

jlP = new JLabel("Parsed:");

JPanel jp = new JPanel();

JTextField jtI = new JTextField( 10 ),

jtD = new JTextField( 10 ),

jtP = new JTextField( 10 );

public JDFDP()

{

super( "JDFDP" );

addWindowListener( this );

jb.addActionListener( this );

jp.add(jlI);

jp.add(jtI);

jp.add(jb);

jp.add(jlD);

jp.add(jtD);

jp.add(jlP);

jp.add(jtP);

getContentPane().add( jp, BorderLayout.CENTER );

© Copyright : IT Engg Portal – www.itportal.in 200

pack();

// set text by sending dummy event

jtI.setText( dfLocal.format( jsqlDate ) );

actionPerformed(

new ActionEvent( this, 12, "12" ) );

show();

} // end constructor

// ActionListener Implementation

public void actionPerformed(ActionEvent e)

{

jtD.setText( "" );

jtP.setText( "" );

try

{

java.util.Date d = dfLocal.parse(

jtI.getText() );

jtI.setText( dfLocal.format( d ) );

jtD.setText( dfGermany.format( d ) );

d = dfGermany.parse( jtD.getText() );

// get new java.sql.Date

jsqlDate = new java.sql.Date( d.getTime() );

jtP.setText( jsqlDate.toString() );

}

catch( ParseException pe ) { jtI.setText( "" ); }

} // End actionPerformed

// Window Listener Implementation

public void windowOpened(WindowEvent e) {}

public void windowClosing(WindowEvent e)

© Copyright : IT Engg Portal – www.itportal.in 201

{

dispose();

System.exit(0);

}

public void windowClosed(WindowEvent e) {}

public void windowIconified(WindowEvent e) {}

public void windowDeiconified(WindowEvent e) {}

public void windowActivated(WindowEvent e) {}

public void windowDeactivated(WindowEvent e) {}

// End Window Listener Implementation

public static void main(String[] args)

{

new JDFDP();

}

} // end class JDFDP

How can I retrieve string data from a database in Unicode format? The data is already in Unicode when it arrives

in your program. Conversion from and to the

encoding/charset/CCSID in the database from/to

Unicode in the program is part of the JDBC driver's job.

If, for some reason, you want to see the data in

'\uHHHH' format ( where 'H' is the hex value ),

the following code, while not very efficient,

should give you some ideas:

public class UniFormat

{

public static void main( String[] args )

{

char[] ac = args[0].toCharArray();

© Copyright : IT Engg Portal – www.itportal.in 202

int iValue;

String s = null;

StringBuffer sb = new StringBuffer();

for( int ndx = 0; ndx < ac.length; ndx++ )

{

iValue = ac[ndx];

if( iValue < 0x10 )

{

s = "\\u000";

}

else

if( iValue < 0x100 )

{

s = "\\u00";

}

else

if( iValue < 0x1000 )

{

s = "\\u0";

}

sb.append( s + Integer.toHexString( iValue ) );

} // end for

System.out.println("The Unicode format of " +

args[0] + " is " + sb );

} // end main

} // end class UniFormat

Can ResultSets be passed between methods of a class? Are there any special

usage

Yes. There is no reason that a ResultSet can't be used as a method parameter just like

any other object reference. You must ensure that access to the ResultSet is

© Copyright : IT Engg Portal – www.itportal.in 203

synchronized. This should not be a problem is the ResultSet is a method variable

passed as a method parameter - the ResultSet will have method scope and multi-thread

access would not be an issue.

As an example, say you have several methods that obtain a ResultSet from the same

table(s) and same columns, but use different queries. If you want these ResultSets to

be processed the same way, you would have another method for that. This could look

something like:

public List getStudentsByLastName(String lastName) {

ResultSet rs = ... (JDBC code to retrieve students by last name);

return processResultSet(rs);

}

public List getStudentsByFirstName(String firstName) {

ResultSet rs = ... (JDBC code to retrieve students by first name);

return processResultSet(rs);

}

private List processResultSet(ResultSet rs) {

List l = ... (code that iterates through ResultSet to build a List of Student objects);

return l;

}

Since the ResultSet always has method scope - sychronization is never an issue.

1. There is only one ResultSet. Dont assume that the ResultSet is at the start (or in any

good state...) just because you received it as a parameter. Previous operations

involving the ResultSet will have had the side-effect of changing its state.

2. You will need to be careful about the order in which you close the ResultSet and

CallableStatement/PreparedStatement/etc

From my own experience using the Oracle JDBC drivers and CallableStatements the

following statements are true:

* If you close the CallableStatement the ResultSet retrieved from that

CallableStatement immediately goes out-of-scope.

© Copyright : IT Engg Portal – www.itportal.in 204

* If you close the ResultSet without reading it fully, you must close the

CallableStatement or risk leaking a cursor on the database server.

* If you close the CallableStatement without reading it's associated ResultSet fully,

you risk leaking a cursor on the database server.

No doubt, these observations are valid only for Oracle drivers. Perhaps only for some

versions of Oracle drivers.

The recommended sequence seems to be:

* Open the statement

* Retrieve the ResultSet from the statement

* Read what you need from the ResultSet

* Close the ResultSet

* Close the Statement

How can I convert a java array to a java.sql.Array? A Java array is a first class object and all of the references basically use

PreparedStatement.setObject() or ResultSet.updateObject() methods for putting the

array to an ARRAY in the database. Here's a basic example:

String[] as = { "One", "Two", "Three" };

...

PreparedStatement ps = con.prepareStatement(

"UPDATE MYTABLE SET ArrayNums = ? WHERE MyKey = ?" );

...

ps.setObject( 1, as );

Could we get sample code for retrieving more than one parameter from a stored

procedure? Assume we have a stored procedure with this signature:

MultiSP (IN I1 INTEGER, OUT O1 INTEGER, INOUT IO1 INTEGER)

The code snippet to retrieve the OUT and INOUT parameters follows:

CallableStatement cs = connection.prepareCall( "(CALL MultiSP(?, ?, ?))" );

cs.setInt(1, 1); // set the IN parm I1 to 1

cs.setInt(3, 3); // set the INOUT parm IO1 to 3

cs.registerOutParameter(2, Types.INTEGER); // register the OUT parm O1

cs.registerOutParameter(3, Types.INTEGER); // register the INOUT parm IO1

© Copyright : IT Engg Portal – www.itportal.in 205

cs.execute();

int iParm2 = cs.getInt(2);

int iParm3 = cs.getInt(3);

cs.close();

The code really is just additive; be sure that for each IN parameter that setXXX() is

called and that for each INOUT and OUT parameter that registerOutParameter() is

called.

What is the difference between client and server database cursors? What you see on the client side is the current row of the cursor which called a Result

(ODBC) or ResultSet (JDBC). The cursor is a server-side entity only and remains on

the server side.

How can I pool my database connections so I don't have to keep reconnecting to

the database? There are plenty of connection pool implementations described in books or availalble

on the net. Most of them implement the same model. The process is always the same :

* you gets a reference to the pool

* you gets a free connection from the pool

* you performs your different tasks

* you frees the connection to the pool

Since your application retrieves a pooled connection, you don't consume your time to

connect / disconnect from your data source. You can find some implementation of

pooled connection over the net, for example:

* Db Connection Broker (http://www.javaexchange.com/), a package quite stable ( I

used it in the past to pool an ORACLE database on VMS system)

You can look at the JDBC 2.0 standard extension API specification from SUN which

defines a number of additional concepts.

How can I connect to an Excel spreadsheet file using jdbc?

Let's say you have created the following Excel spreadsheet in a worksheet called

Sheet1 (the default sheet name). And you've saved the file in c:\users.xls.

© Copyright : IT Engg Portal – www.itportal.in 206

USERID FIRST_NAME LAST_NAME

pkua Peter Kua

jlsmith John Smith

gh2312 Everett Johnson

chimera Faiz Abdullah

roy6943 Roy Sudirman

Since Excel comes with an ODBC driver, we'll use the JDBC-ODBC bridge driver

that comes packaged with Sun's JDK to connect to our spreadsheet.

In Excel, the name of the worksheet is the equivalent of the database table name, while

the header names found on the first row of the worksheet is the equivalent of the table

field names. Therefore, when accessing Excel via jdbc, it is very important to place

your data with the headers starting at row 1.

1. Create a new ODBC Data Source using the Microsoft Excel Driver. Name the DSN

"excel", and have it point to c:\users.xls.

2. Type in the following code:

package classes;

import java.sql.*;

public class TestServer

{

static

{

try {

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

}

catch (Exception e) {

System.err.println(e);

}

}

public static void main(String args[]) {

Connection conn=null;

Statement stmt=null;

String sql="";

ResultSet rs=null;

© Copyright : IT Engg Portal – www.itportal.in 207

try {

conn=DriverManager.getConnection("jdbc:odbc:excel","","");

stmt=conn.createStatement();

sql="select * from [Sheet1$]";

rs=stmt.executeQuery(sql);

while(rs.next()){

System.out.println(rs.getString("USERID")+

" "+ rs.getString("FIRST_NAME")+" "+

rs.getString("LAST_NAME"));

}

}

catch (Exception e){

System.err.println(e);

}

finally {

try{

rs.close();

stmt.close();

conn.close();

rs=null;

stmt=null;

conn=null;

}

catch(Exception e){}

}

}

}

Notice that we have connected to the Excel ODBC Data Source the same way we

would connect to any normal database server.

The only significant difference is in the SELECT statement. Although your data is

residing in the worksheet called "Sheet1", you'll have to refer to the sheet as Sheet1$

in your SQL statements. And because the dollar sign symbol is a reserved character in

SQL, you'll have to encapsulate the word Sheet1$ in brackets, as shown in the code.

© Copyright : IT Engg Portal – www.itportal.in 208

How do I execute stored procedures? Here is an example on how to execute a stored procedure with JDBC (to use this in a

servlet is the same the only thing is that you create the connection and callable

statement in the init() of the servlet):

package DBTest;

import java.sql.*;

public class JdbcTest {

private String msDbUrl = "jdbc:odbc:ms";

private String msJdbcClass = "sun.jdbc.odbc.JdbcOdbcDriver";

private Connection mcDbAccess;

private CallableStatement msProcedure;

public JdbcTest() {

try {

Class.forName( msDbUrl ).newInstance();

mcDbAccess = DriverManager.getConnection( msJdbcClass, "milestone", "milestone"

);

msProcedure = mcDbAccess.prepareCall(

"{? = call sp_sav_Bom_Header( ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? ) }"

);

msProcedure.registerOutParameter( 1, java.sql.Types.VARCHAR );

msProcedure.setInt( 2, -1 );

msProcedure.setInt( 3, 39 );

msProcedure.setString( 4, "format" );

long ltTest = new java.util.Date().getTime();

System.out.println( "Today: " + ltTest );

msProcedure.setTimestamp( 5, new Timestamp( ltTest ) );

msProcedure.setString( 6, "type" );

msProcedure.setString( 7, "submitter" );

msProcedure.setString( 8, "email" );

msProcedure.setString( 9, "phone" );

msProcedure.setString( 10, "comments" );

msProcedure.setString( 11, "label" );

msProcedure.setInt( 12, 52 );

msProcedure.setBoolean( 13, true );

msProcedure.setBoolean( 14, false );

© Copyright : IT Engg Portal – www.itportal.in 209

msProcedure.setInt( 15, 53 );

msProcedure.setString( 16, "runtime" );

msProcedure.setString( 17, "configuration" );

msProcedure.setBoolean( 18, true );

msProcedure.setBoolean( 19, false );

msProcedure.setString( 20, "special instructions" );

msProcedure.setInt( 21, 54 );

ResultSet lrsReturn = null;

System.out.println( "Execute: " + (lrsReturn = msProcedure.executeQuery() ) );

while( lrsReturn.next() ) {

System.out.println( "Got from result set: " + lrsReturn.getInt( 1 ) );

}

System.out.println( "Got from stored procedure: " + msProcedure.getString( 1 ) );

} catch( Throwable e ) {

e.printStackTrace();

}

}

public static void main(String[] args) {

new JdbcTest();

}

}

I also tried it by using a native JDBC driver (i-net) and it also works fine. The only

problem we encounter with JDBC-ODBC bridge is that a stored procedure pads spaces

to the full length of a VARCHAR but the native JDBC behaves right. Therefore I

suggest to use JDBC native drivers.

The above example uses the MS SQL Server.

How can I get data from multiple ResultSets?

With certain database systems, a stored procedure can return multiple result sets,

multiple update counts, or some combination of both. Also, if you are providing a user

with the ability to enter any SQL statement, you don't know if you are going to get a

ResultSet or an update count back from each statement, without analyzing the

contents. The Statement.execute() method helps in these cases.

Method Statement.execute() returns a boolean to tell you the type of response:

© Copyright : IT Engg Portal – www.itportal.in 210

* true indicates next result is a ResultSet

Use Statement.getResultSet to get the ResultSet

* false indicates next result is an update count

Use Statement.getUpdateCount to get the update count

* false also indicates no more results

Update count is -1 when no more results (usually 0 or positive)

After processing each response, you use Statement.getMoreResults to check for more

results, again returning a boolean. The following demonstrates the processing of

multiple result sets:

boolean result = stmt.execute(" ... ");

int updateCount = stmt.getUpdateCount();

while (result || (updateCount != -1)) {

if(result) {

ResultSet r = stmt.getResultSet();

// process result set

} else if(updateCount != -1) {

// process update count

}

result = stmt.getMoreResults();

updateCount = stmt.getUpdateCount();

}

How can resultset records be restricted to certain rows? The easy answer is "Use a JDBC 2.0 compliant driver".

With a 2.0 driver, you can use the setFetchSize() method within a Statement or a

ResultSet object.

For example,

Statement stmt = con.createStatement();

stmt.setFetchSize(400);

ResultSet rs = stmt.executeQuery("select * from customers");

will change the default fetch size to 400.

You can also control the direction in which the rows are processed. For instance:

© Copyright : IT Engg Portal – www.itportal.in 211

stmt.setFetchDirection(ResultSet.FETCH_REVERSE)

will process the rows from bottom up.

The driver manager usually defaults to the most efficient fetch size...so you may try

experimenting with different value for optimal performance.

How do I insert an image file (or other raw data) into a database? All raw data types (including binary documents or images) should be read and

uploaded to the database as an array of bytes, byte[]. Originating from a binary file,

1. Read all data from the file using a FileInputStream.

2. Create a byte array from the read data.

3. Use method setBytes(int index, byte[] data); of java.sql.PreparedStatement to

upload the data.

How can I connect from an applet to a database on the server? There are two ways of connecting to a database on the server side.

1. The hard way. Untrusted applets cannot touch the hard disk of a computer. Thus,

your applet cannot use native or other local files (such as JDBC database drivers) on

your hard drive. The first alternative solution is to create a digitally signed applet

which may use locally installed JDBC drivers, able to connect directly to the database

on the server side.

2. The easy way. Untrusted applets may only open a network connection to the server

from which they were downloaded. Thus, you must place a database listener (either

the database itself, or a middleware server) on the server node from which the applet

was downloaded. The applet would open a socket connection to the middleware

server, located on the same computer node as the webserver from which the applet

was downloaded. The middleware server is used as a mediator, connecting to and

extract data from the database.

Can I use the JDBC-ODBC bridge driver in an applet? Short answer: No.

Longer answer: You may create a digitally signed applet using a Certicate to

circumvent the security sandbox of the browser.

Which is the preferred collection class to use for storing database result sets? When retrieving database results, the best collection implementation to use is the

LinkedList. The benefits include:

* Retains the original retrieval order

© Copyright : IT Engg Portal – www.itportal.in 212

* Has quick insertion at the head/tail

* Doesn't have an internal size limitation like a Vector where when the size is

exceeded a new internal structure is created (or you have to find out size beforehand to

size properly)

* Permits user-controlled synchronization unlike the pre-Collections Vector which is

always synchronized

Basically:

ResultSet result = stmt.executeQuery("...");

List list = new LinkedList();

while(result.next()) {

list.add(result.getString("col"));

}

If there are multiple columns in the result set, you'll have to combine them into their

own data structure for each row. Arrays work well for that as you know the size,

though a custom class might be best so you can convert the contents to the proper type

when extracting from databse, instead of later.

The java.sql package contains mostly interfaces. When and how are these

interfaces implemented while connecting to database? The implementation of these interfaces is all part of the driver. A JDBC driver is not

just one class - it is a complete set of database-specific implementations for the

interfaces defined by the JDBC.

These driver classes come into being through a bootstrap process. This is best shown

by stepping through the process of using JDBC to connect to a database, using

Oracle's type 4 JDBC driver as an example:

* First, the main driver class must be loaded into the VM:

Class.forName("oracle.jdbc.driver.OracleDriver");

The specified driver must implement the Driver interface. A class initializer (static

code block) within the OracleDriver class registers the driver with the DriverManager.

* Next, we need to obtain a connection to the database:

String jdbcURL = "jdbc:oracle:thin:@www.jguru.com:1521:ORCL";

Connection connection = DriverManager.getConnection(jdbcURL);

DriverManager determines which registered driver to use by invoking the

acceptsURL(String url) method of each driver, passing each the JDBC URL. The first

© Copyright : IT Engg Portal – www.itportal.in 213

driver to return "true" in response will be used for this connection. In this example,

OracleDriver will return "true", so DriverManager then invokes the connect() method

of OracleDriver to obtain an instance of OracleConnection. It is this database-specific

connection instance implementing the Connection interface that is passed back from

the DriverManager.getConnection() call.

* The bootstrap process continues when you create a statement:

Statement statement = connection.createStatement();

The connection reference points to an instance of OracleConnection. This database-

specific implementation of Connection returns a database-specific implementation of

Statement, namely OracleStatement

* Invoking the execute() method of this statement object will execute the database-

specific code necessary to issue an SQL statement and retrieve the results:

ResultSet result = statement.executeQuery("SELECT * FROM TABLE");

Again, what is actually returned is an instance of OracleResultSet, which is an Oracle-

specific implementation of the ResultSet interface.

So the purpose of a JDBC driver is to provide these implementations that hide all the

database-specific details behind standard Java interfaces.

How can I manage special characters (for example: " _ ' % ) when I execute an

INSERT query? If I don't filter the quoting marks or the apostrophe, for

example, the SQL string will cause an error. In JDBC, strings containing SQL commands are just normal strings - the SQL is not

parsed or interpreted by the Java compiler. So there is no special mechanism for

dealing with special characters; if you need to use a quote (") within a Java string, you

must escape it.

The Java programming language supports all the standard C escapes, such as \n for

newline, \t for tab, etc. In this case, you would use \" to represent a quote within a

string literal:

String stringWithQuote =

"\"No,\" he replied, \"I did not like that salted licorice.\"";

This only takes care of one part of the problem: letting us control the exact string that

is passed on to the database. If you want tell the database to interpret characters like a

single quote (') literally (and not as string delimiters, for instance), you need to use a

different method. JDBC allows you to specify a separate, SQL escape character that

causes the character following to be interpreted literally, rather than as a special

© Copyright : IT Engg Portal – www.itportal.in 214

character.

An example of this is if you want to issue the following SQL command:

SELECT * FROM BIRDS

WHERE SPECIES='Williamson's Sapsucker'

In this case, the apostrophe in "Williamson's" is going to cause a problem for the

database because SQL will interpret it as a string delimiter. It is not good enough to

use the C-style escape \', because that substitution would be made by the Java compiler

before the string is sent to the database.

Different flavors of SQL provide different methods to deal with this situation. JDBC

abstracts these methods and provides a solution that works for all databases. With

JDBC you could write the SQL as follows:

Statement statement = // obtain reference to a Statement

statement.executeQuery(

"SELECT * FROM BIRDS WHERE SPECIES='Williamson/'s Sapsucker' {escape

'/'}");

The clause in curly braces, namely {escape '/'}, is special syntax used to inform JDBC

drivers what character the programmer has chosen as an escape character. The forward

slash used as the SQL escape has no special meaning to the Java compiler; this escape

sequence is interpreted by the JDBC driver and translated into database-specific SQL

before the SQL command is issued to the database.

Escape characters are also important when using the SQL LIKE clause. This usage is

explicitly addressed in section 11.5 of the JDBC specification:

The characters "%" and "_" have special meaning in SQL LIKE clauses (to match zero

or more characters, or exactly one character, respectively). In order to interpret them

literally, they can be preceded with a special escape character in strings, e.g. "\". In

order to specify the escape character used to quote these characters, include the

following syntax on the end of the query:

{escape 'escape-character'}

For example, the query

SELECT NAME FROM IDENTIFIERS WHERE ID LIKE '\_%' {escape '\'}

finds identifier names that begin with an underbar.

© Copyright : IT Engg Portal – www.itportal.in 215

How can I make batch updates using JDBC?

One of the more advanced features of JDBC 2.0 is the ability to submit multiple

update statements to the database for processing as a single unit. This batch updating

can be significantly more efficient compared to JDBC 1.0, where each update

statement has to be executed separately.

Consider the following code segment demonstrating a batch update:

try {

dbCon.setAutoCommit(false);

Statement stmt= dbCon.createStatement();

stmt.addBatch("INSERT INTO bugs "+

"VALUES (1007, 'Server stack overflow', 1,2,{d '1999-01-01'})");

stmt.addBatch("INSERT INTO bugs "+

"VALUES (1008,'Cannot load DLL', 3,1,{d '1999-01-01'})");

stmt.addBatch("INSERT INTO bugs "+

"VALUES (1009,'Applet locks up',2,2,{d '1999-01-01'})");

int[] updCnt = stmt.executeBatch();

dbCon.commit();

} catch (BatchUpdateException be) {

//handle batch update exception

int[] counts = be.getUpdateCounts();

for (int i=0; I counts.length; i++) {

System.out.println("Statement["+i+"] :"+counts[i]);

}

dbCon.rollback();

}

catch (SQLException e) {

//handle SQL exception

dbCon.rollback();

}

Before carrying out a batch update, it is important to disable the auto-commit mode by

calling setAutoCommit(false). This way, you will be able to rollback the batch

© Copyright : IT Engg Portal – www.itportal.in 216

transaction in case one of the updates fail for any reason. When the Statement object is

created, it is automatically associated a "command list", which is initially empty. We

then add our SQL update statements to this command list, by making successive calls

to the addBatch() method. On calling executeBatch(), the entire command list is sent

over to the database, and are then executed in the order they were added to the list. If

all the commands in the list are executed successfully, their corresponding update

counts are returned as an array of integers. Please note that you always have to clear

the existing batch by calling clearBatch() before creating a new one.

If any of the updates fail to execute within the database, a BatchUpdateException is

thrown in response to it. In case there is a problem in returning the update counts of

each SQL statement, a SQLException will be thrown to indicate the error.

How do I extract SQL table column type information? Use the getColumns method of the java.sql.DatabaseMetaData interface to investigate

the column type information of a particular table. Note that most arguments to the

getColumns method (pinpointing the column in question) may be null, to broaden the

search criteria. A code sample can be seen below:

public static void main(String[] args) throws Exception

{

// Load the database driver - in this case, we

// use the Jdbc/Odbc bridge driver.

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

// Open a connection to the database

Connection conn = DriverManager.getConnection("[jdbcURL]",

"[login]", "[passwd]");

// Get DatabaseMetaData

DatabaseMetaData dbmd = conn.getMetaData();

// Get all column types for the table "sysforeignkeys", in schema

// "dbo" and catalog "test".

ResultSet rs = dbmd.getColumns("test", "dbo", "sysforeignkeys", "%");

// Printout table data

while(rs.next())

© Copyright : IT Engg Portal – www.itportal.in 217

{

// Get dbObject metadata

String dbObjectCatalog = rs.getString(1);

String dbObjectSchema = rs.getString(2);

String dbObjectName = rs.getString(3);

String dbColumnName = rs.getString(4);

String dbColumnTypeName = rs.getString(6);

int dbColumnSize = rs.getInt(7);

int dbDecimalDigits = rs.getInt(9);

String dbColumnDefault = rs.getString(13);

int dbOrdinalPosition = rs.getInt(17);

String dbColumnIsNullable = rs.getString(18);

// Printout

System.out.println("Col(" + dbOrdinalPosition + "): " + dbColumnName

+ " (" + dbColumnTypeName +")");

System.out.println(" Nullable: " + dbColumnIsNullable +

", Size: " + dbColumnSize);

System.out.println(" Position in table: " + dbOrdinalPosition

+ ", Decimal digits: " + dbDecimalDigits);

}

// Free database resources

rs.close();

conn.close();

}

How can I investigate the parameters to send into and receive from a database

stored procedure?

Use the method getProcedureColumns in interface DatabaseMetaData to probe a

stored procedure for metadata. The exact usage is described in the code below.

NOTE! This method can only discover parameter values. For databases where a

returning ResultSet is created simply by executing a SELECT statement within a

stored procedure (thus not sending the return ResultSet to the java application via a

declared parameter), the real return value of the stored procedure cannot be detected.

This is a weakness for the JDBC metadata mining which is especially present when

© Copyright : IT Engg Portal – www.itportal.in 218

handling Transact-SQL databases such as those produced by SyBase and Microsoft.

public static void main(String[] args) throws Exception

{

// Load the database driver - in this case, we

// use the Jdbc/Odbc bridge driver.

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver")

;

// Open a connection to the database

Connection conn = DriverManager.getConnection("[jdbcURL]",

"[login]", "[passwd]");

// Get DatabaseMetaData

DatabaseMetaData dbmd = conn.getMetaData();

// Get all column definitions for procedure "getFoodsEaten" in

// schema "testlogin" and catalog "dbo".

System.out.println("Procedures are called '" + dbmd.getProcedureTerm() +"' in the

DBMS.");

ResultSet rs = dbmd.getProcedureColumns("test", "dbo", "getFoodsEaten", "%");

// Printout table data

while(rs.next())

{

// Get procedure metadata

String dbProcedureCatalog = rs.getString(1);

String dbProcedureSchema = rs.getString(2);

String dbProcedureName = rs.getString(3);

String dbColumnName = rs.getString(4);

short dbColumnReturn = rs.getShort(5);

String dbColumnReturnTypeName = rs.getString(7);

int dbColumnPrecision = rs.getInt(8);

int dbColumnByteLength = rs.getInt(9);

short dbColumnScale = rs.getShort(10);

short dbColumnRadix = rs.getShort(11);

String dbColumnRemarks = rs.getString(13);

© Copyright : IT Engg Portal – www.itportal.in 219

// Interpret the return type (readable for humans)

String procReturn = null;

switch(dbColumnReturn)

{

case DatabaseMetaData.procedureColumnIn:

procReturn = "In";

break;

case DatabaseMetaData.procedureColumnOut:

procReturn = "Out";

break;

case DatabaseMetaData.procedureColumnInOut:

procReturn = "In/Out";

break;

case DatabaseMetaData.procedureColumnReturn:

procReturn = "return value";

break;

case DatabaseMetaData.procedureColumnResult:

procReturn = "return ResultSet";

default:

procReturn = "Unknown";

}

// Printout

System.out.println("Procedure: " + dbProcedureCatalog + "." + dbProcedureSchema

+ "." + dbProcedureName);

System.out.println(" ColumnName [ColumnType(ColumnPrecision)]: " +

dbColumnName

+ " [" + dbColumnReturnTypeName + "(" + dbColumnPrecision + ")]");

System.out.println(" ColumnReturns: " + procReturn + "(" +

dbColumnReturnTypeName + ")");

System.out.println(" Radix: " + dbColumnRadix + ", Scale: " + dbColumnScale);

System.out.println(" Remarks: " + dbColumnRemarks);

}

// Close database resources

© Copyright : IT Engg Portal – www.itportal.in 220

rs.close();

conn.close();

}

How do I check what table-like database objects (table, view, temporary table,

alias) are present in a particular database? Use java.sql.DatabaseMetaData to probe the database for metadata. Use the getTables

method to retrieve information about all database objects (i.e. tables, views, system

tables, temporary global or local tables or aliases). The exact usage is described in the

code below.

NOTE! Certain JDBC drivers throw IllegalCursorStateExceptions when you try to

access fields in the ResultSet in the wrong order (i.e. not consecutively). Thus, you

should not change the order in which you retrieve the metadata from the ResultSet.

public static void main(String[] args) throws Exception

{

// Load the database driver - in this case, we

// use the Jdbc/Odbc bridge driver.

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

// Open a connection to the database

Connection conn = DriverManager.getConnection("[jdbcURL]",

"[login]", "[passwd]");

// Get DatabaseMetaData

DatabaseMetaData dbmd = conn.getMetaData();

// Get all dbObjects. Replace the last argument in the getTables

// method with objectCategories below to obtain only database

// tables. (Sending in null retrievs all dbObjects).

String[] objectCategories = {"TABLE"};

ResultSet rs = dbmd.getTables(null, null, "%", null);

// Printout table data

while(rs.next())

{

© Copyright : IT Engg Portal – www.itportal.in 221

// Get dbObject metadata

String dbObjectCatalog = rs.getString(1);

String dbObjectSchema = rs.getString(2);

String dbObjectName = rs.getString(3);

String dbObjectType = rs.getString(4);

// Printout

System.out.println("" + dbObjectType + ": " + dbObjectName);

System.out.println(" Catalog: " + dbObjectCatalog);

System.out.println(" Schema: " + dbObjectSchema);

}

// Close database resources

rs.close();

conn.close();

}

What does ResultSet actually contain? Is it the actual data of the result or some

links to databases? If it is the actual data then why can't we access it after

connection is closed?

A ResultSet is an interface. Its implementation depends on the driver and hence ,what

it "contains" depends partially on the driver and what the query returns.

For example with the Odbc bridge what the underlying implementation layer contains

is an ODBC result set. A Type 4 driver executing a stored procedure that returns a

cursor - on an oracle database it actually returns a cursor in the databse. The oracle

cursor can however be processed like a ResultSet would be from the client. Closing a

connection closes all interaction with the database and releases any locks that might

have been obtained in the process.

How do I extract the SQL statements required to move all tables and views from

an existing database to another database? The operation is performed in 9 steps:

1. Open a connection to the source database. Use the DriverManager class.

2. Find the entire physical layout of the current database. Use the DatabaseMetaData

interface.

3. Create DDL SQL statements for re-creating the current database structure. Use the

DatabaseMetaData interface.

© Copyright : IT Engg Portal – www.itportal.in 222

4. Build a dependency tree, to determine the order in which tables must be setup. Use

the DatabaseMetaData interface.

5. Open a connection to the target database. Use the DriverManager class.

6. Execute all DDL SQL statements from (3) in the order given by (4) in the target

database to setup the table and view structure. Use the PreparedStatement interface.

7. If (6) threw exceptions, abort the entire process.

8. Loop over all tables in the physical structure to generate DML SQL statements for

re-creating the data inside the table. Use the ResultSetMetaData interface.

9. Execute all DML SQL statements from (8) in the target database.

How do I check what table types exist in a database? Use the getTableTypes method of interface java.sql.DatabaseMetaData to probe the

database for table types. The exact usage is described in the code below.

public static void main(String[] args) throws Exception

{

// Load the database driver - in this case, we

// use the Jdbc/Odbc bridge driver.

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

// Open a connection to the database

Connection conn = DriverManager.getConnection("[jdbcURL]",

"[login]", "[passwd]");

// Get DatabaseMetaData

DatabaseMetaData dbmd = conn.getMetaData();

// Get all table types.

ResultSet rs = dbmd.getTableTypes();

// Printout table data

while(rs.next())

{

// Printout

System.out.println("Type: " + rs.getString(1));

}

© Copyright : IT Engg Portal – www.itportal.in 223

// Close database resources

rs.close();

conn.close();

}

What is the advantage of using a PreparedStatement? For SQL statements that are executed repeatedly, using a PreparedStatement object

would almost always be faster than using a Statement object. This is because creating

a PreparedStatement object by explicitly giving the SQL statement causes the

statement to be precompiled within the database immediately. Thus, when the

PreparedStatement is later executed, the DBMS does not have to recompile the SQL

statement and prepared an execution plan - it simply runs the statement.

Typically, PreparedStatement objects are used for SQL statements that take

parameters. However, they can also be used with repeatedly executed SQL statements

that do not accept parameters.

How do I find all database stored procedures in a database?

Use the getProcedures method of interface java.sql.DatabaseMetaData to probe the

database for stored procedures. The exact usage is described in the code below.

public static void main(String[] args) throws Exception

{

// Load the database driver - in this case, we

// use the Jdbc/Odbc bridge driver.

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

// Open a connection to the database

Connection conn = DriverManager.getConnection("[jdbcURL]",

"[login]", "[passwd]");

// Get DatabaseMetaData

DatabaseMetaData dbmd = conn.getMetaData();

// Get all procedures.

System.out.println("Procedures are called '"

+ dbmd.getProcedureTerm() +"' in the DBMS.");

ResultSet rs = dbmd.getProcedures(null, null, "%");

© Copyright : IT Engg Portal – www.itportal.in 224

// Printout table data

while(rs.next())

{

// Get procedure metadata

String dbProcedureCatalog = rs.getString(1);

String dbProcedureSchema = rs.getString(2);

String dbProcedureName = rs.getString(3);

String dbProcedureRemarks = rs.getString(7);

short dbProcedureType = rs.getShort(8);

// Make result readable for humans

String procReturn = (dbProcedureType == DatabaseMetaData.procedureNoResult

? "No Result" : "Result");

// Printout

System.out.println("Procedure: " + dbProcedureName

+ ", returns: " + procReturn);

System.out.println(" [Catalog | Schema]: [" + dbProcedureCatalog

+ " | " + dbProcedureSchema + "]");

System.out.println(" Comments: " + dbProcedureRemarks);

}

// Close database resources

rs.close();

conn.close();

}

How can I investigate the physical structure of a database?

The JDBC view of a database internal structure can be seen in the image below.

* Several database objects (tables, views, procedures etc.) are contained within a

Schema.

* Several schema (user namespaces) are contained within a catalog.

* Several catalogs (database partitions; databases) are contained within a DB server

(such as Oracle, MS SQL

© Copyright : IT Engg Portal – www.itportal.in 225

The DatabaseMetaData interface has methods for discovering all the Catalogs,

Schemas, Tables and Stored Procedures in the database server. The methods are pretty

intuitive, returning a ResultSet with a single String column; use them as indicated in

the code below:

public static void main(String[] args) throws Exception

{

// Load the database driver - in this case, we

// use the Jdbc/Odbc bridge driver.

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

// Open a connection to the database

Connection conn = DriverManager.getConnection("[jdbcURL]",

"[login]", "[passwd]");

// Get DatabaseMetaData

DatabaseMetaData dbmd = conn.getMetaData();

// Get all Catalogs

System.out.println("\nCatalogs are called '" + dbmd.getCatalogTerm()

+ "' in this RDBMS.");

processResultSet(dbmd.getCatalogTerm(), dbmd.getCatalogs());

// Get all Schemas

System.out.println("\nSchemas are called '" + dbmd.getSchemaTerm()

+ "' in this RDBMS.");

processResultSet(dbmd.getSchemaTerm(), dbmd.getSchemas());

// Get all Table-like types

System.out.println("\nAll table types supported in this RDBMS:");

processResultSet("Table type", dbmd.getTableTypes());

// Close the Connection

conn.close();

}

public static void processResultSet(String preamble, ResultSet rs)

throws SQLException

© Copyright : IT Engg Portal – www.itportal.in 226

{

// Printout table data

while(rs.next())

{

// Printout

System.out.println(preamble + ": " + rs.getString(1));

}

// Close database resources

rs.close();

}

How does the Java Database Connectivity (JDBC) work? The JDBC is used whenever a Java application should communicate with a relational

database for which a JDBC driver exists. JDBC is part of the Java platform standard;

all visible classes used in the Java/database communication are placed in package

java.sql.

Main JDBC classes:

* DriverManager. Manages a list of database drivers. Matches connection requests

from the java application with the proper database driver using communication

subprotocol. The first driver that recognizes a certain subprotocol under jdbc (such as

odbc or dbAnywhere/dbaw) will be used to establish a database Connection.

* Driver. The database communications link, handling all communication with the

database. Normally, once the driver is loaded, the developer need not call it explicitly.

* Connection. Interface with all methods for contacting a database

* Statement. Encapsulates an SQL statement which is passed to the database to be

parsed, compiled, planned and executed.

* ResultSet. The answer/result from a statement. A ResultSet is a fancy 2D list which

encapsulates all outgoing results from a given SQL query.

What is Metadata and why should I use it? Metadata ('data about data') is information about one of two things:

1. Database information (java.sql.DatabaseMetaData), or

2. Information about a specific ResultSet (java.sql.ResultSetMetaData).

Use DatabaseMetaData to find information about your database, such as its

© Copyright : IT Engg Portal – www.itportal.in 227

capabilities and structure. Use ResultSetMetaData to find information about the results

of an SQL query, such as size and types of columns.

How do I create a database connection? The database connection is created in 3 steps:

1. Find a proper database URL (see FAQ on JDBC URL)

2. Load the database driver

3. Ask the Java DriverManager class to open a connection to your database

In java code, the steps are realized in code as follows:

1. Create a properly formatted JDBR URL for your database. (See FAQ on JDBC

URL for more information). A JDBC URL has the form

jdbc:someSubProtocol://myDatabaseServer/theDatabaseName

2.

try {

Class.forName("my.database.driver");

}

catch(Exception ex)

{

System.err.println("Could not load database driver: " + ex);

}

3. Connection conn = DriverManager.getConnection("a.JDBC.URL",

"databaseLogin", "databasePassword");

© Copyright : IT Engg Portal – www.itportal.in 228

Servlet

Interview Questions &

Answers

© Copyright : IT Engg Portal – www.itportal.in 229

Servlet Interview Questions and Answers

What is Servlet?

A servlet is a Java technology-based Web component, managed by a container called

servlet container or servlet engine, that generates dynamic content and interacts with

web clients via a request\/response paradigm.

Why is Servlet so popular? Because servlets are platform-independent Java classes that are compiled to platform-

neutral byte code that can be loaded dynamically into and run by a Java technology-

enabled Web server.

What is servlet container?

The servlet container is a part of a Web server or application server that provides the

network services over which requests and responses are sent, decodes MIME-based

requests, and formats MIME-based responses. A servlet container also contains and

manages servlets through their lifecycle.

When a client request is sent to the servlet container, how does the container

choose which servlet to invoke? The servlet container determines which servlet to invoke based on the configuration of

its servlets, and calls it with objects representing the request and response.

If a servlet is not properly initialized, what exception may be thrown? During initialization or service of a request, the servlet instance can throw an

UnavailableException or a ServletException.

Given the request path below, which are context path, servlet path and path

info? /bookstore/education/index.html

context path: /bookstore

servlet path: /education

path info: /index.html

What is filter? Can filter be used as request or response? A filter is a reusable piece of code that can transform the content of HTTP

requests,responses, and header information. Filters do not generally create a response

© Copyright : IT Engg Portal – www.itportal.in 230

or respond to a request as servlets do, rather they modify or adapt the requests for a

resource, and modify or adapt responses from a resource.

When using servlets to build the HTML, you build a DOCTYPE line, why do you

do that?

I know all major browsers ignore it even though the HTML 3.2 and 4.0 specifications

require it. But building a DOCTYPE line tells HTML validators which version of

HTML you are using so they know which specification to check your document

against. These validators are valuable debugging services, helping you catch HTML

syntax errors.

What is new in ServletRequest interface ? (Servlet 2.4) The following methods have been added to ServletRequest 2.4 version:

public int getRemotePort()

public java.lang.String getLocalName()

public java.lang.String getLocalAddr()

public int getLocalPort()

Request parameter How to find whether a parameter exists in the request

object?

1.boolean hasFoo = !(request.getParameter("foo") == null ||

request.getParameter("foo").equals(""));

2. boolean hasParameter = request.getParameterMap().contains(theParameter);

(which works in Servlet 2.3+)

How can I send user authentication information while making URL Connection? You'll want to use HttpURLConnection.setRequestProperty and set all the appropriate

headers to HTTP authorization.

Can we use the constructor, instead of init(), to initialize servlet? Yes , of course you can use the constructor instead of init(). There's nothing to stop

you. But you shouldn't. The original reason for init() was that ancient versions of Java

couldn't dynamically invoke constructors with arguments, so there was no way to give

the constructur a ServletConfig. That no longer applies, but servlet containers still will

only call your no-arg constructor. So you won't have access to a ServletConfig or

ServletContext.

© Copyright : IT Engg Portal – www.itportal.in 231

How can a servlet refresh automatically if some new data has entered the

database? You can use a client-side Refresh or Server Push

The code in a finally clause will never fail to execute, right? Using System.exit(1); in try block will not allow finally code to execute.

What mechanisms are used by a Servlet Container to maintain session

information?

Cookies, URL rewriting, and HTTPS protocol information are used to maintain

session information

Difference between GET and POST In GET your entire form submission can be encapsulated in one URL, like a hyperlink.

query length is limited to 260 characters, not secure, faster, quick and easy.

In POST Your name/value pairs inside the body of the HTTP request, which makes

for a cleaner URL and imposes no size limitations on the form's output. It is used to

send a chunk of data to the server to be processed, more versatile, most secure.

What is session? The session is an object used by a servlet to track a user's interaction with a Web

application across multiple HTTP requests.

What is servlet mapping? The servlet mapping defines an association between a URL pattern and a servlet. The

mapping is used to map requests to servlets.

What is servlet context ? The servlet context is an object that contains a servlet's view of the Web application

within which the servlet is running. Using the context, a servlet can log events, obtain

URL references to resources, and set and store attributes that other servlets in the

context can use. (answer supplied by Sun's tutorial).

Which interface must be implemented by all servlets?

Servlet interface.

Explain the life cycle of Servlet.

© Copyright : IT Engg Portal – www.itportal.in 232

Loaded(by the container for first request or on start up if config file suggests load-on-

startup), initialized( using init()), service(service() or doGet() or doPost()..),

destroy(destroy()) and unloaded.

When is the servlet instance created in the life cycle of servlet? What is the

importance of configuring a servlet? An instance of servlet is created when the servlet is loaded for the first time in the

container. Init() method is used to configure this servlet instance. This method is

called only once in the life time of a servlet, hence it makes sense to write all those

configuration details about a servlet which are required for the whole life of a servlet

in this method.

Why don't we write a constructor in a servlet? Container writes a no argument constructor for our servlet.

When we don't write any constructor for the servlet, how does container create

an instance of servlet? Container creates instance of servlet by calling

Class.forName(className).newInstance().

Once the destroy() method is called by the container, will the servlet be

immediately destroyed? What happens to the tasks(threads) that the servlet

might be executing at that time? Yes, but Before calling the destroy() method, the servlet container waits for the

remaining threads that are executing the servlet‘s service() method to finish.

What is the difference between callling a RequestDispatcher using

ServletRequest and ServletContext? We can give relative URL when we use ServletRequest and not while using

ServletContext.

Why is it that we can't give relative URL's when using

ServletContext.getRequestDispatcher() when we can use the same while calling

ServletRequest.getRequestDispatcher()? Since ServletRequest has the current request path to evaluae the relative path while

ServletContext does not.

==============================================

© Copyright : IT Engg Portal – www.itportal.in 233

Data Structures

Interview Questions &

Answers

© Copyright : IT Engg Portal – www.itportal.in 234

Data Structures Interview Questions and Answers

What is data structure? A data structure is a way of organizing data that considers not only the items stored,

but also their relationship to each other. Advance knowledge about the relationship

between data items allows designing of efficient algorithms for the manipulation of

data.

List out the areas in which data structures are applied extensively? Compiler Design, Operating System, Database Management System, Statistical

analysis package, Numerical Analysis, Graphics, Artificial Intelligence, Simulation

If you are using C language to implement the heterogeneous linked list, what

pointer type will you use? The heterogeneous linked list contains different data types in its nodes and we need a

link, pointer to connect them. It is not possible to use ordinary pointers for this. So we

go for void pointer. Void pointer is capable of storing pointer to any type as it is a

generic pointer type.

What is the data structures used to perform recursion? Stack. Because of its LIFO (Last In First Out) property it remembers its caller, so

knows whom to return when the function has to return. Recursion makes use of system

stack for storing the return addresses of the function calls. Every recursive function

has its equivalent iterative (non-recursive) function. Even when such equivalent

iterative procedures are written, explicit stack is to be used.

What are the methods available in storing sequential files ? Straight merging, Natural merging, Polyphase sort, Distribution of Initial runs.

List out few of the Application of tree data-structure? The manipulation of Arithmetic expression, Symbol Table construction, Syntax

analysis.

In RDBMS, what is the efficient data structure used in the internal storage

representation? B+ tree. Because in B+ tree, all the data is stored only in leaf nodes, that makes

searching easier. This corresponds to the records that shall be stored in leaf nodes.

© Copyright : IT Engg Portal – www.itportal.in 235

What is a spanning Tree? A spanning tree is a tree associated with a network. All the nodes of the graph appear

on the tree once. A minimum spanning tree is a spanning tree organized so that the

total edge weight between nodes is minimized.

Does the minimum spanning tree of a graph give the shortest distance between

any 2 specified nodes? Minimal spanning tree assures that the total weight of the tree is kept at its minimum.

But it doesn't mean that the distance between any two nodes involved in the minimum-

spanning tree is minimum.

Whether Linked List is linear or Non-linear data structure? According to Access strategies Linked list is a linear one. According to Storage

Linked List is a Non-linear one.

What is the quickest sorting method to use? The answer depends on what you mean by quickest. For most sorting problems, it just

doesn't matter how quick the sort is because it is done infrequently or other operations

take significantly more time anyway. Even in cases in which sorting speed is of the

essence, there is no one answer. It depends on not only the size and nature of the data,

but also the likely order. No algorithm is best in all cases. There are three sorting

methods in this author's toolbox that are all very fast and that are useful in different

situations. Those methods are quick sort, merge sort, and radix sort.

The Quick Sort

The quick sort algorithm is of the divide and conquer type. That means it works by

reducing a sorting problem into several easier sorting problems and solving each of

them. A dividing value is chosen from the input data, and the data is partitioned into

three sets: elements that belong before the dividing value, the value itself, and

elements that come after the dividing value. The partitioning is performed by

exchanging elements that are in the first set but belong in the third with elements that

are in the third set but belong in the first Elements that are equal to the dividing

element can be put in any of the three sets the algorithm will still work properly.

The Merge Sort

The merge sort is a divide and conquer sort as well. It works by considering the data to

be sorted as a sequence of already-sorted lists (in the worst case, each list is one

© Copyright : IT Engg Portal – www.itportal.in 236

element long). Adjacent sorted lists are merged into larger sorted lists until there is a

single sorted list containing all the elements. The merge sort is good at sorting lists and

other data structures that are not in arrays, and it can be used to sort things that don't fit

into memory. It also can be implemented as a stable sort.

The Radix Sort

The radix sort takes a list of integers and puts each element on a smaller list,

depending on the value of its least significant byte. Then the small lists are

concatenated, and the process is repeated for each more significant byte until the list is

sorted. The radix sort is simpler to implement on fixed-length data such as ints.

How can I search for data in a linked list? Unfortunately, the only way to search a linked list is with a linear search, because the

only way a linked list's members can be accessed is sequentially. Sometimes it is

quicker to take the data from a linked list and store it in a different data structure so

that searches can be more efficient.

What is the heap? The heap is where malloc(), calloc(), and realloc() get memory.

Getting memory from the heap is much slower than getting it from the stack. On the

other hand, the heap is much more flexible than the stack. Memory can be allocated at

any time and deallocated in any order. Such memory isn't deallocated automatically;

you have to call free().

Recursive data structures are almost always implemented with memory from the heap.

Strings often come from there too, especially strings that could be very long at

runtime. If you can keep data in a local variable (and allocate it from the stack), your

code will run faster than if you put the data on the heap. Sometimes you can use a

better algorithm if you use the heap faster, or more robust, or more flexible. Its a

tradeoff.

If memory is allocated from the heap, its available until the program ends. That's great

if you remember to deallocate it when you're done. If you forget, it's a problem. A

�memory leak is some allocated memory that's no longer needed but isn't

deallocated. If you have a memory leak inside a loop, you can use up all the memory

on the heap and not be able to get any more. (When that happens, the allocation

functions return a null pointer.) In some environments, if a program doesn't deallocate

everything it allocated, memory stays unavailable even after the program ends.

© Copyright : IT Engg Portal – www.itportal.in 237

What is the easiest sorting method to use? The answer is the standard library function qsort(). It's the easiest sort by far for

several reasons:

It is already written.

It is already debugged.

It has been optimized as much as possible (usually).

Void qsort(void *buf, size_t num, size_t size, int (*comp)(const void *ele1, const void

*ele2));

What is the bucket size, when the overlapping and collision occur at same time? One. If there is only one entry possible in the bucket, when the collision occurs, there

is no way to accommodate the colliding value. This results in the overlapping of

values.

In an AVL tree, at what condition the balancing is to be done? If the pivotal value (or the Height factor) is greater than 1 or less than 1.

Minimum number of queues needed to implement the priority queue? Two. One queue is used for actual storing of data and another for storing priorities.

How many different trees are possible with 10 nodes ? 1014 - For example, consider a tree with 3 nodes(n=3), it will have the maximum

combination of 5 different (ie, 23 - 3 =? 5) trees.

What is a node class? A node class is a class that, relies on the base class for services and implementation,

provides a wider interface to users than its base class, relies primarily on virtual

functions in its public interface depends on all its direct and indirect base class can be

understood only in the context of the base class can be used as base for further

derivation

can be used to create objects. A node class is a class that has added new services or

functionality beyond the services inherited from its base class.

When can you tell that a memory leak will occur? A memory leak occurs when a program loses the ability to free a block of dynamically

allocated memory.

© Copyright : IT Engg Portal – www.itportal.in 238

What is placement new? When you want to call a constructor directly, you use the placement new. Sometimes

you have some raw memory that‘s already been allocated, and you need to construct

an object in the memory you have. Operator new‘s special version placement new

allows you to do it.

class Widget

{

public :

Widget(int widgetsize);

Widget* Construct_widget_int_buffer(void *buffer,int widgetsize)

{

return new(buffer) Widget(widgetsize);

}

};

This function returns a pointer to a Widget object that‘s constructed within the buffer

passed to the function. Such a function might be useful for applications using shared

memory or memory-mapped I/O, because objects in such applications must be placed

at specific addresses or in memory allocated by special routines.

List out the areas in which data structures are applied extensively ? Compiler Design, Operating System, Database Management System, Statistical

analysis package, Numerical Analysis, Graphics, Artificial Intelligence, Simulation

If you are using C language to implement the heterogeneous linked list, what

pointer type will you use? The heterogeneous linked list contains different data types in its nodes and we need a

link, pointer to connect them. It is not possible to use ordinary pointers for this. So we

go for void pointer. Void pointer is capable of storing pointer to any type as it is a

generic pointer type.

What is the data structures used to perform recursion? Stack. Because of its LIFO (Last In First Out) property it remembers its caller so

knows whom to return when the function has to return. Recursion makes use of system

stack for storing the return addresses of the function calls. Every recursive function

has its equivalent iterative (non-recursive) function. Even when such equivalent

iterative procedures are written, explicit stack is to be used.

© Copyright : IT Engg Portal – www.itportal.in 239

Whether Linked List is linear or Non-linear data structure? According to Access strategies Linked list is a linear one.

According to Storage Linked List is a Non-linear one

Tell how to check whether a linked list is circular ? Create two pointers, each set to the start of the list. Update each as follows:

while (pointer1)

{

pointer1 = pointer1->next;

pointer2 = pointer2->next; if (pointer2) pointer2=pointer2->next;

if (pointer1 == pointer2)

? ? ? ? ? ? {

print (\‖circular\n\‖);

}

}

What is the difference between ARRAY and STACK? STACK follows LIFO. Thus the item that is first entered would be the last removed.

In array the items can be entered or removed in any order. Basically each member

access is done using index. No strict order is to be followed here to remove a

particular element.

What is the difference between NULL AND VOID pointer? NULL can be value for pointer type variables.

VOID is a type identifier which has not size.

NULL and void are not same. Example: void* ptr = NULL;

What is precision? Precision refers the accuracy of the decimal portion of a value. Precision is the number

of digits allowed after the decimal point.

What is impact of signed numbers on the memory? Sign of the number is the first bit of the storage allocated for that number. So you get

© Copyright : IT Engg Portal – www.itportal.in 240

one bit less for storing the number. For example if you are storing an 8-bit number,

without sign, the range is 0-255. If you decide to store sign you get 7 bits for the

number plus one bit for the sign. So the range is -128 to +127.

How memory is reserved using a declaration statement ? Memory is reserved using data type in the variable declaration. A programming

language implementation has predefined sizes for its data types.

For example, in C# the declaration int i; will reserve 32 bits for variable i.

A pointer declaration reserves memory for the address or the pointer variable, but not

for the data that it will point to. The memory for the data pointed by a pointer has to be

allocated at runtime.

The memory reserved by the compiler for simple variables and for storing pointer

address is allocated on the stack, while the memory allocated for pointer referenced

data at runtime is allocated on the heap.

How many parts are there in a declaration statement? There are two main parts, variable identifier and data type and the third type is

optional which is type qualifier like signed/unsigned.

Is Pointer a variable? Yes, a pointer is a variable and can be used as an element of a structure and as an

attribute of a class in some programming languages such as C++, but not Java.

However, the contents of a pointer is a memory address of another location of

memory, which is usually the memory address of another variable, element of a

structure, or attribute of a class.

What is Data Structure? A data structure is a group of data elements grouped together under one name. These

data elements, known as members, can have different types and different lengths.

Some are used to store the data of same type and some are used to store different types

of data.

What is significance of ” * ” ? The symbol ―*‖ tells the computer that you are declaring a pointer.

Actually it depends on context.

© Copyright : IT Engg Portal – www.itportal.in 241

In a statement like int *ptr; the ‗*‘ tells that you are declaring a pointer.

In a statement like int i = *ptr; it tells that you want to assign value pointed to by ptr to

variable i.

The symbol ―*‖ is also called as Indirection Operator/ Dereferencing Operator.

Why do we Use a Multidimensional Array? A multidimensional array can be useful to organize subgroups of data within an array.

In addition to organizing data stored in elements of an array, a multidimensional array

can store memory addresses of data in a pointer array and an array of pointers.

Multidimensional arrays are used to store information in a matrix form.

e.g. a railway timetable, schedule cannot be stored as a single dimensional array.

One can use a 3-D array for storing height, width and length of each room on each

floor of a building.

How do you assign an address to an element of a pointer array ? We can assign a memory address to an element of a pointer array by using the address

operator, which is the ampersand (&), in an assignment statement such as

ptemployee[0] = &projects[2];

Run Time Memory Allocation is known as ? Allocating memory at runtime is called a dynamically allocating memory. In this, you

dynamically allocate memory by using the new operator when declaring the array, for

example : int grades[] = new int[10];

What method is used to place a value onto the top of a stack? push() method, Push is the direction that data is being added to the stack. push()

member method places a value onto the top of a stack.

What method removes the value from the top of a stack? The pop() member method removes the value from the top of a stack, which is then

returned by the pop() member method to the statement that calls the pop() member

method.

What does isEmpty() member method determines? isEmpty() checks if the stack has at least one element. This method is called by Pop()

before retrieving and returning the top element.

© Copyright : IT Engg Portal – www.itportal.in 242

What is a queue ? A Queue is a sequential organization of data. A queue is a first in first out type of data

structure. An element is inserted at the last position and an element is always taken out

from the first position.

What is the relationship between a queue and its underlying array? Data stored in a queue is actually stored in an array. Two indexes, front and end will

be used to identify the start and end of the queue.

When an element is removed front will be incremented by 1. In case it reaches past the

last index available it will be reset to 0. Then it will be checked with end. If it is

greater than end queue is empty.

When an element is added end will be incremented by 1. In case it reaches past the last

index available it will be reset to 0. After incrementing it will be checked with front. If

they are equal queue is full.

Which process places data at the back of the queue? Enqueue is the process that places data at the back of the queue.

Why is the isEmpty() member method called? The isEmpty() member method is called within the dequeue process to determine if

there is an item in the queue to be removed i.e. isEmpty() is called to decide whether

the queue has at least one element. This method is called by the dequeue() method

before returning the front element.

How is the front of the queue calculated ? The front of the queue is calculated by front = (front+1) % size.

What does each entry in the Link List called? Each entry in a linked list is called a node. Think of a node as an entry that has three

sub entries. One sub entry contains the data, which may be one attribute or many

attributes. Another points to the previous node, and the last points to the next node.

When you enter a new item on a linked list, you allocate the new node and then set the

pointers to previous and next nodes.

What is Linked List ? Linked List is one of the fundamental data structures. It consists of a sequence of?

© Copyright : IT Engg Portal – www.itportal.in 243

nodes, each containing arbitrary data fields and one or two (‖links‖) pointing to the

next and/or previous nodes. A linked list is a self-referential datatype because it

contains a pointer or link to another data of the same type. Linked lists permit insertion

and removal of nodes at any point in the list in constant time, but do not allow random

access.

What member function places a new node at the end of the linked list? The appendNode() member function places a new node at the end of the linked list.

The appendNode() requires an integer representing the current data of the node.

How is any Data Structure application is classified among files? A linked list application can be organized into a header file, source file and main

application file. The first file is the header file that contains the definition of the

NODE structure and the LinkedList class definition. The second file is a source code

file containing the implementation of member functions of the LinkedList class. The

last file is the application file that contains code that creates and uses the LinkedList

class.

Which file contains the definition of member functions? Definitions of member functions for the Linked List class are contained in the

LinkedList.cpp file.

What are the major data structures used in the following areas : RDBMS,

Network data model & Hierarchical data model. 1. RDBMS Array (i.e. Array of structures)

2. Network data model Graph

3. Hierarchical data model Trees.

Difference between calloc and malloc ? malloc: allocate n bytes

calloc: allocate m times n bytes initialized to 0

=====================================================

© Copyright : IT Engg Portal – www.itportal.in 244

Networking

Interview Questions &

Answers

© Copyright : IT Engg Portal – www.itportal.in 245

Networking Interview Questions and Answers

What is an Object server?

With an object server, the Client/Server application is written as a set of

communicating objects. Client object communicate with server objects using an

Object Request Broker (ORB). The client invokes a method on a remote object. The

ORB locates an instance of that object server class, invokes the requested method and

returns the results to the client object. Server objects must provide support for

concurrency and sharing. The ORB brings it all together.

What is a Transaction server?

With a transaction server, the client invokes remote procedures that reside on the

server with an SQL database engine. These remote procedures on the server execute a

group of SQL statements. The network exchange consists of a single request/reply

message. The SQL statements either all succeed or fail as a unit.

What is a Database Server?

With a database server, the client passes SQL requests as messages to the database

server. The results of each SQL command are returned over the network. The server

uses its own processing power to find the request data instead of passing all the

records back to the client and then getting it find its own data. The result is a much

more efficient use of distributed processing power. It is also known as SQL engine.

What are the most typical functional units of the Client/Server applications?

User interface

Business Logic and

Shared data.

What are all the Extended services provided by the OS?

Ubiquitous communications

Network OS extension

Binary large objects (BLOBs)

Global directories and Network yellow pages

Authentication and Authorization services

System management

Network time

Database and transaction services

© Copyright : IT Engg Portal – www.itportal.in 246

Internet services

Object- oriented services

What are Triggers and Rules? Triggers are special user defined actions usually in the form of stored procedures, that

are automatically invoked by the server based on data related events. It can perform

complex actions and can use the full power of procedural languages.

A rule is a special type of trigger that is used to perform simple checks on data.

What is meant by Transparency?

Transparency really means hiding the network and its servers from the users and even

the application programmers.

What are TP-Lite and TP-Heavy Monitors?

TP-Lite is simply the integration of TP Monitor functions in the database engines. TP-

Heavy are TP Monitors which supports the Client/Server architecture and allow PC to

initiate some very complex multiserver transaction from the desktop.

What are the two types of OLTP? TP lite, based on stored procedures. TP heavy, based on the TP monitors.

What is a Web server? This new model of Client/Server consists of thin, protable, "universal" clients that talk

to superfat servers. In the simplet form, a web server returns documents when clients

ask for them by name. The clients and server communicate using an RPC-like protocol

called HTTP.

What are Super servers?

These are fully-loaded machines which includes multiprocessors, high-speed disk

arrays for intervive I/O and fault tolerant features.

What is a TP Monitor?

There is no commonly accepted definition for a TP monitor. According to Jeri

Edwards' a TP Monitor is "an OS for transaction processing".

TP Monitor does mainly two things extremely well. They are Process

management and Transaction management.?

They were originally introduced to run classes of applications that could service

hundreds and sometimes thousands of clients. TP Monitors provide an OS - on top of

© Copyright : IT Engg Portal – www.itportal.in 247

existing OS - that connects in real time these thousands of humans with a pool of

shared server processes.

What is meant by Asymmetrical protocols?

There is a many-to-one relationship between clients and server. Clients always initiate

the dialog by requesting a service. Servers are passively awaiting for requests from

clients.

What are the types of Transparencies?

The types of transparencies the NOS middleware is expected to provide are:-

Location transparency

Namespace transparency

Logon transparency

Replication transparency

Local/Remote access transparency

Distributed time transparency

Failure transparency and

Administration transparency.

What is the difference between trigger and rule?

The triggers are called implicitly by database generated events, while stored

procedures are called explicitly by client applications.

What are called Transactions?

The grouped SQL statements are called Transactions (or) A transaction is a collection

of actions embused with ACID properties.

What are the building blocks of Client/Server?

The client

The server and

Middleware.

Explain the building blocks of Client/Server?

The client side building block runs the client side of the application.

The server side building block runs the server side of the application.

The middleware buliding block runs on both the client and server sides of an

application. It is broken into three categories:-

© Copyright : IT Engg Portal – www.itportal.in 248

Transport stack

Network OS

Service-specific middleware.

What are all the Base services provided by the OS?

Task preemption

Task priority

Semaphores

Interprocess communications (IPC)

Local/Remote Interprocess communication

Threads

Intertask protection

Multiuser

High performance file system

Efficient memory management and

Dynamically linked Run-time extensions.

What are the roles of SQL?

SQL is an interactive query language for ad hoc database queries.

SQL is a database programming language.

SQL is a data definition and data administration language.

SQL is the language of networked database servers

SQL helps protect the data in a multi-user networked environment.

Because of these multifacted roles it plays, physicists might call SQL as "The grand

unified theory of database".

What are the characteristics of Client/Server?

Service

Shared resources

Asymmentrical protocols

Transparency of location

Mix-and-match

Message based exchanges

Encapsulation of services

Scalability

Integrity

Client/Server computing is the ultimate "Open platform". It gives the freedom to mix-

© Copyright : IT Engg Portal – www.itportal.in 249

and-match components of almost any level. Clients and servers are loosely coupled

systems that interact through a message-passing mechanism.

What is Structured Query Langauge (SQL)?

SQL is a powerful set-oriented language which was developed by IBM research for

the databases that adhere to the relational model. It consists of a short list of powerful,

yet highly flexible, commands that can be used to manipulate information collected in

tables. Through SQL, we can manipulate and control sets of records at a time.

What is Remote Procedure Call (RPC)?

RPC hides the intricacies of the network by using the ordinary procedure call

mechanism familiar to every programmer. A client process calls a function on a

remote server and suspends itself until it gets back the results. Parameters are passed

like in any ordinary procedure. The RPC, like an ordinary procedure, is synchoronous.

The process that issues the call waits until it gets the results.

Under the covers, the RPC run-time software collects values for the parameters, forms

a message, and sends it to the remote server. The server receives the request, unpack

the parameters, calls the procedures, and sends the reply back to the client. It is a

telephone-like metaphor.

What are the main components of Transaction-based Systems?

Resource Manager

Transaction Manager and

Application Program.

What are the three types of SQL database server architecture?

Process-per-client Architecture. (Example: Oracle 6, Informix )

Multithreaded Architecture. (Example: Sybase, SQL server)

Hybrid Architecture

What are the Classification of clients?

Non-GUI clients - Two types are:-

Non-GUI clients that do not need multi-tasking

(Example: Automatic Teller Machines (ATM), Cell phone)

Non-GUI clients that need multi-tasking

(Example: ROBOTs)

© Copyright : IT Engg Portal – www.itportal.in 250

GUI clients

OOUI clients

What are called Non-GUI clients, GUI Clients and OOUI Clients?

Non-GUI Client: These are applications, generate server requests with a minimal

amount of human interaction.

GUI Clients: These are applicatoins, where occassional requests to the server result

from a human interacting with a GUI

(Example: Windows 3.x, NT 3.5)

OOUI clients : These are applications, which are highly-iconic, object-oriented user

interface that provides seamless access to information in very visual formats.

(Example: MAC OS, Windows 95, NT 4.0)

What is Message Oriented Middleware (MOM)?

MOM allows general purpose messages to be exchanged in a Client/Server system

using message queues. Applications communicate over networks by simply putting

messages in the queues and getting messages from queues. It typically provides a very

simple high level APIs to its services.

MOM's messaging and queuing allow clients and servers to communicate across a

network without being linked by a private, dedicated, logical connection. The clients

and server can run at different times. It is a post-office like metaphor.

What is meant by Middleware?

Middleware is a distributed software needed to support interaction between clients and

servers. In short, it is the software that is in the middle of the Client/Server systems

and it acts as a bridge between the clients and servers. It starts with the API set on the

client side that is used to invoke a service and it covers the transmission of the request

over the network and the resulting response.

It neither includes the software that provides the actual service - that is in the servers

domain nor the user interface or the application login - that's in clients domain.

What are the functions of the typical server program?

It waits for client-initiated requests. Executes many requests at the same time. Takes

care of VIP clients first. Initiates and runs background task activity. Keeps running.

Grown bigger and faster.

What is meant by Symmentric Multiprocessing (SMP)?

It treats all processors as equal. Any processor can do the work of any other processor.

© Copyright : IT Engg Portal – www.itportal.in 251

Applications are divided into threads that can run concurrently on any available

processor. Any processor in the pool can run the OS kernel and execute user-written

threads.

What are General Middleware?

It includes the communication stacks, distributed directories, authentication services,

network time, RPC, Queuing services along with the network OS extensions such as

the distributed file and print services.

What are Service-specific middleware?

It is needed to accomplish a particular Client/Server type of services which includes:-

Database specific middleware

OLTP specific middleware

Groupware specific middleware

Object specific middleware

Internet specific middleware and

System management specific middleware.

What is meant by Asymmetric Multiprocessing (AMP)?

It imposses hierarchy and a division of labour among processors. Only one designated

processor, the master, controls (in a tightly coupled arrangement) slave processors

dedicated to specific functions.

What is OLTP?

In the transaction server, the client component usually includes GUI and the server

components usually consists of SQL transactions against a database. These

applications are called OLTP (Online Transaction Processing) OLTP Applications

typically,

Receive a fixed set of inputs from remote clients. Perform multiple pre-compiled SQL

comments against a local database. Commit the work and Return a fixed set of results.

What is meant by 3-Tier architecture?

In 3-tier Client/Server systems, the application logic (or process) lives in the middle

tier and it is separated from the data and the user interface. In theory, the 3-tier

Client/Server systems are more scalable, robust and flexible.

Example: TP monitor, Web.

© Copyright : IT Engg Portal – www.itportal.in 252

What is meant by 2-Tier architecture?

In 2-tier Client/Server systems, the application logic is either burried inside the user

interface on the client or within the database on the server.

Example: File servers and Database servers with stored procedures.

What is Load balancing?

If the number of incoming clients requests exceeds the number of processes in a server

class, the TP Monitor may dynamically start new ones and this is called Load

balancing.

What are called Fat clients and Fat servers?

If the bulk of the application runs on the Client side, then it is Fat clients. It is used for

decision support and personal software.

If the bulk of the application runs on the Server side, then it is Fat servers. It tries to

minimize network interchanges by creating more abstract levels of services.

What is meant by Horizontal scaling and Vertical scaling?

Horizontal scaling means adding or removing client workstations with only a slight

performance impact. Vertical scaling means migrating to a larger and faster server

machine or multiservers.

What is Groupware server?

Groupware addresses the management of semi-structured information such as text,

image, mail, bulletin boards and the flow of work. These Client/Server systems have

people in direct contact with other people.

What are the two broad classes of middleware?

General middleware

Service-specific middleware.

What are the types of Servers?

File servers

Database servers Transaction servers Groupware servers Object servers Web servers.

What is a File server?

File servers are useful for sharing files across a network. With a file server, the client

passes requests for file records over nerwork to file server.

© Copyright : IT Engg Portal – www.itportal.in 253

What are the five major technologies that can be used to create Client/Server

applications?

Database Servers

TP Monitors

Groupware

Distributed Objects

Intranets.

What is Client/Server?

Clients and Servers are separate logical entities that work together over a network to

accomplish a task. Many systems with very different architectures that are connected

together are also called Client/Server.

List out the benefits obtained by using the Client/Server oriented TP Monitors? Client/Server applications development framework.

Firewalls of protection.

High availability.

Load balancing.

MOM integration.

Scalability of functions.

Reduced system cost.

What are the services provided by the Operating System? Extended services - These are add-on modular software components that are layered

on top of base service.

What is ACID property? ACID is a term coined by Andrew Reuter in 1983, which stands for Atomicity,

Consistence, Isolation and Durability.

What are Stored procedures?

A stored procedure i s named collection of SQL statements and procedural logic that is

compiled, verified and stored in a server database. It is typically treated like any other

database object. Stored procedures accept input parameters so that a single procedure

can be used over the network by multiple clients using different input data. A single

© Copyright : IT Engg Portal – www.itportal.in 254

remote message triggers the execution of a collection of stored SQL statements. The

results is a reduction of network traffic and better performance.

What is wide-mouth frog?

Wide-mouth frog is the simplest known key distribution center (KDC) authentication

protocol.

What is passive topology?

When the computers on the network simply listen and receive the signal, they are

referred to as passive because they don‘t amplify the signal in any way.

Example for passive topology - linear bus.

What is region?

When hierarchical routing is used, the routers are divided into what we call regions,

with each router knowing all the details about how to route packets to destinations

within its own region, but knowing nothing about the internal structure of other

regions.

What is virtual channel?

Virtual channel is normally a connection from one source to one destination, although

multicast connections are also permitted. The other name for virtual channel is virtual

circuit.

Difference between the communication and transmission?

Transmission is a physical movement of information and concern issues like bit

polarity, synchronization, clock etc.

Communication means the meaning full exchange of information between two

communication media.

What is the difference between TFTP and FTP application layer protocols?

The Trivial File Transfer Protocol (TFTP) allows a local host to obtain files from a

remote host but does not provide reliability or security. It uses the fundamental packet

delivery services offered by UDP.

The File Transfer Protocol (FTP) is the standard mechanism provided by TCP / IP for

copying a file from one host to another. It uses the services offered by TCP and so is

reliable and secure. It establishes two connections (virtual circuits) between the hosts,

one for data transfer and another for control information.

© Copyright : IT Engg Portal – www.itportal.in 255

What are the advantages and disadvantages of the three types of routing tables?

The three types of routing tables are fixed, dynamic, and fixed central. The fixed table

must be manually modified every time there is a change. A dynamic table changes its

information based on network traffic, reducing the amount of manual maintenance. A

fixed central table lets a manager modify only one table, which is then read by other

devices. The fixed central table reduces the need to update each machine's table, as

with the fixed table. Usually a dynamic table causes the fewest problems for a network

administrator, although the table's contents can change without the administrator being

aware of the change.

What is Beaconing?

The process that allows a network to self-repair networks problems. The stations on

the network notify the other stations on the ring when they are not receiving the

transmissions. Beaconing is used in Token ring and FDDI networks.

What does the Mount protocol do ?

The Mount protocol returns a file handle and the name of the file system in which a

requested file resides. The message is sent to the client from the server after reception

of a client's request.

What are Digrams and Trigrams?

The most common two letter combinations are called as digrams. e.g. th, in, er, re and

an. The most common three letter combinations are called as trigrams. e.g. the, ing,

and, and ion.

What is the HELLO protocol used for?

The HELLO protocol uses time instead of distance to determine optimal routing. It is

an alternative to the Routing Information Protocol.

What is the minimum and maximum length of the header in the TCP segment

and IP datagram?

The header should have a minimum length of 20 bytes and can have a maximum

length of 60 bytes.

What do you meant by "triple X" in Networks?

The function of PAD (Packet Assembler Disassembler) is described in a document

known as X.3. The standard protocol has been defined between the terminal and the

© Copyright : IT Engg Portal – www.itportal.in 256

PAD, called X.28; another standard protocol exists between the PAD and the network,

called X.29. Together, these three recommendations are often called "triple X".

What is attenuation?

The degeneration of a signal over distance on a network cable is called attenuation.

What is Protocol Data Unit?

The data unit in the LLC level is called the protocol data unit (PDU). The PDU

contains of four fields a destination service access point (DSAP), a source service

access point (SSAP), a control field and an information field. DSAP, SSAP are

addresses used by the LLC to identify the protocol stacks on the receiving and sending

machines that are generating and using the data. The control field specifies whether

the PDU frame is a information frame (I - frame) or a supervisory frame (S - frame) or

a unnumbered frame (U - frame).

What are the data units at different layers of the TCP / IP protocol suite?

The data unit created at the application layer is called a message, at the transport layer

the data unit created is called either a segment or an user datagram, at the network

layer the data unit created is called the datagram, at the data link layer the datagram is

encapsulated in to a frame and finally transmitted as signals along the transmission

media.

What is difference between ARP and RARP?

The address resolution protocol (ARP) is used to associate the 32 bit IP address with

the 48 bit physical address, used by a host or a router to find the physical address of

another host on its network by sending a ARP query packet that includes the IP

address of the receiver.

The reverse address resolution protocol (RARP) allows a host to discover its Internet

address when it knows only its physical address.

What is MAC address?

The address for a device as it is identified at the Media Access Control (MAC) layer in

the network architecture. MAC address is usually stored in ROM on the network

adapter card and is unique.

What is terminal emulation, in which layer it comes?

Telnet is also called as terminal emulation. It belongs to application layer.

© Copyright : IT Engg Portal – www.itportal.in 257

What are the types of Transmission media?

Signals are usually transmitted over some transmission media that are broadly

classified in to two categories:-

Guided Media:

These are those that provide a conduit from one device to another that include twisted-

pair, coaxial cable and fiber-optic cable. A signal traveling along any of these media is

directed and is contained by the physical limits of the medium. Twisted-pair and

coaxial cable use metallic that accept and transport signals in the form of electrical

current. Optical fiber is a glass or plastic cable that accepts and transports signals in

the form of light.

Unguided Media:

This is the wireless media that transport electromagnetic waves without using a

physical conductor. Signals are broadcast either through air. This is done through radio

communication, satellite communication and cellular telephony.

What are major types of networks and explain?

Server-based network.

Peer-to-peer network.

Peer-to-peer network, computers can act as both servers sharing resources and as

clients using the resources.

Server-based networks provide centralized control of network resources and rely on

server computers to provide security and network administration.

What is SAP?

Series of interface points that allow other computers to communicate with the other

layers of network protocol stack.

What is multicast routing?

Sending a message to a group is called multicasting, and its routing algorithm is called

multicast routing.

© Copyright : IT Engg Portal – www.itportal.in 258

What is the difference between routable and non- routable protocols?

Routable protocols can work with a router and can be used to build large networks.

Non-Routable protocols are designed to work on small, local networks and cannot be

used with a router.

What is REX?

Request to Exit (REX) - A signal that informs the controller that someone has

requested to exit from a secure area.

What are the different type of networking / internetworking devices?

Repeater:

Also called a regenerator, it is an electronic device that operates only at physical layer.

It receives the signal in the network before it becomes weak, regenerates the original

bit pattern and puts the refreshed copy back in to the link.

Bridges: These operate both in the physical and data link layers of LANs of same type. They

divide a larger network in to smaller segments. They contain logic that allow them to

keep the traffic for each segment separate and thus are repeaters that relay a frame

only the side of the segment containing the intended recipent and control congestion.

Routers: They relay packets among multiple interconnected networks (i.e. LANs of different

type). They operate in the physical, data link and network layers. They contain

software that enable them to determine which of the several possible paths is the best

for a particular transmission. Gateways: They relay packets among networks that have

different protocols (e.g. between a LAN and a WAN). They accept a packet formatted

for one protocol and convert it to a packet formatted for another protocol before

forwarding it. They operate in all seven layers of the OSI model.

What is redirector?

Redirector is software that intercepts file or prints I/O requests and translates them into

network requests. This comes under presentation layer.

What is packet filter?

Packet filter is a standard router equipped with some extra functionality. The extra

functionality allows every incoming or outgoing packet to be inspected. Packets

meeting some criterion are forwarded normally. Those that fail the test are dropped.

© Copyright : IT Engg Portal – www.itportal.in 259

What is logical link control?

One of two sublayers of the data link layer of OSI reference model, as defined by the

IEEE 802 standard. This sublayer is responsible for maintaining the link between

computers when they are sending data across the physical network connection.

What is traffic shaping?

One of the main causes of congestion is that traffic is often busy. If hosts could be

made to transmit at a uniform rate, congestion would be less common. Another open

loop method to help manage congestion is forcing the packet to be transmitted at a

more predictable rate. This is called traffic shaping.

What is NETBIOS and NETBEUI?

NETBIOS is a programming interface that allows I/O requests to be sent to and

received from a remote computer and it hides the networking hardware from

applications.

NETBEUI is NetBIOS extended user interface. A transport protocol designed by

microsoft and IBM for the use on small subnets.

Why should you care about the OSI Reference Model?

It provides a framework for discussing network operations and design.

What is Proxy ARP?

is using a router to answer ARP requests. This will be done when the originating host

believes that a destination is local, when in fact is lies beyond router.

What is EGP (Exterior Gateway Protocol)?

It is the protocol the routers in neighboring autonomous systems use to identify the set

of networks that can be reached within or via each autonomous system.

What is IGP (Interior Gateway Protocol)?

It is any routing protocol used within an autonomous system.

What is OSPF?

It is an Internet routing protocol that scales well, can route traffic along multiple paths,

and uses knowledge of an Internet's topology to make accurate routing decisions.

What is Kerberos?

It is an authentication service developed at the Massachusetts Institute of Technology.

© Copyright : IT Engg Portal – www.itportal.in 260

Kerberos uses encryption to prevent intruders from discovering passwords and gaining

unauthorized access to files.

What is SLIP (Serial Line Interface Protocol)?

It is a very simple protocol used for transmission of IP datagrams across a serial line.

What is Mail Gateway?

It is a system that performs a protocol translation between different electronic mail

delivery protocols.

What is RIP (Routing Information Protocol)?

It is a simple protocol used to exchange information between the routers.

What is NVT (Network Virtual Terminal)?

It is a set of rules defining a very simple virtual terminal interaction. The NVT is used

in the start of a Telnet session.

What is source route?

It is a sequence of IP addresses identifying the route a datagram must follow. A source

route may optionally be included in an IP datagram header.

What is BGP (Border Gateway Protocol)?

It is a protocol used to advertise the set of networks that can be reached with in an

autonomous system. BGP enables this information to be shared with the autonomous

system. This is newer than EGP (Exterior Gateway Protocol).

What is Gateway-to-Gateway protocol?

It is a protocol formerly used to exchange routing information between Internet core

routers.

What is Project 802?

It is a project started by IEEE to set standards that enable intercommunication between

equipment from a variety of manufacturers. It is a way for specifying functions of the

physical layer, the data link layer and to some extent the network layer to allow for

interconnectivity of major LAN protocols.

It consists of the following:

802.1 is an internetworking standard for compatibility of different LANs and MANs

across protocols.

802.2 Logical link control (LLC) is the upper sublayer of the data link layer which is

© Copyright : IT Engg Portal – www.itportal.in 261

non-architecture-specific, that is remains the same for all IEEE-defined LANs. Media

access control (MAC) is the lower sublayer of the data link layer that contains some

distinct modules each carrying proprietary information specific to the LAN product

being used. The modules are

Ethernet LAN (802.3), Token ring LAN (802.4), Token bus LAN (802.5).

802.6 is distributed queue dual bus (DQDB) designed to be used in MANs.

What is silly window syndrome?

It is a problem that can ruin TCP performance. This problem occurs when data are

passed to the sending TCP entity in large blocks, but an interactive application on the

receiving side reads 1 byte at a time.

What is a Multi-homed Host?

It is a host that has a multiple network interfaces and that requires multiple IP

addresses is called as a Multi-homed Host.

What is autonomous system?

It is a collection of routers under the control of a single administrative authority and

that uses a common Interior Gateway Protocol.

What is the difference between interior and exterior neighbor gateways?

Interior gateways connect LANs of one organization, whereas exterior gateways

connect the organization to the outside world.

What is MAU?

In token Ring , hub is called Multistation Access Unit(MAU).

Explain 5-4-3 rule.?

In a Ethernet network, between any two points on the network, there can be no more

than five network segments or four repeaters, and of those five segments only three of

segments can be populated.

What is difference between baseband and broadband transmission?

In a baseband transmission, the entire bandwidth of the cable is consumed by a single

signal. In broadband transmission, signals are sent on multiple frequencies, allowing

multiple signals to be sent simultaneously.

What is ICMP?

ICMP is Internet Control Message Protocol, a network layer protocol of the TCP/IP

© Copyright : IT Engg Portal – www.itportal.in 262

suite used by hosts and gateways to send notification of datagram problems back to the

sender. It uses the echo test / reply to test whether a destination is reachable and

responding. It also handles both control and error messages.

What is Brouter?

Hybrid devices that combine the features of both bridges and routers.

What is frame relay, in which layer it comes?

Frame relay is a packet switching technology. It will operate in the data link layer.

What is External Data Representation?

External Data Representation is a method of encoding data within an RPC message,

used to ensure that the data is not system-dependent.

What is Bandwidth?

Every line has an upper limit and a lower limit on the frequency of signals it can carry.

This limited range is called the bandwidth.

What protocol is used by DNS name servers?

DNS uses UDP for communication between servers. It is a better choice than TCP

because of the improved speed a connectionless protocol offers. Of course,

transmission reliability suffers with UDP.

What is the range of addresses in the classes of internet addresses? Class A 0.0.0.0 - 127.255.255.255

Class B 128.0.0.0 - 191.255.255.255

Class C 192.0.0.0 - 223.255.255.255

Class D 224.0.0.0 - 239.255.255.255

Class E 240.0.0.0 - 247.255.255.255

What are the important topologies for networks?

BUS topology:

In this each computer is directly connected to primary network cable in a single line.

Advantages:

Inexpensive, easy to install, simple to understand, easy to extend.

STAR topology:

In this all computers are connected using a central hub.

Advantages:

© Copyright : IT Engg Portal – www.itportal.in 263

Can be inexpensive, easy to install and reconfigure and easy to trouble shoot physical

problems.

RING topology:

In this all computers are connected in loop.

Advantages:

All computers have equal access to network media, installation can be simple, and

signal does not degrade as much as in other topologies because each computer

regenerates it.

Difference between bit rate and baud rate?

Bit rate is the number of bits transmitted during one second whereas baud rate refers to

the number of signal units per second that are required to represent those bits.

baud rate = bit rate / N

where N is no-of-bits represented by each signal shift.

What is anonymous FTP and why would you use it?

Anonymous FTP enables users to connect to a host without using a valid login and

password. Usually, anonymous FTP uses a login called anonymous or guest, with the

password usually requesting the user's ID for tracking purposes only. Anonymous FTP

is used to enable a large number of users to access files on the host without having to

go to the trouble of setting up logins for them all. Anonymous FTP systems usually

have strict controls over the areas an anonymous user can access.

What is the difference between an unspecified passive open and a fully specified

passive open?

An unspecified passive open has the server waiting for a connection request from a

client. A fully specified passive open has the server waiting for a connection from a

specific client.

What is virtual path?

Along any transmission path from a given source to a given destination, a group of

virtual circuits can be grouped together into what is called path.

Explain the function of Transmission Control Block?

A TCB is a complex data structure that contains a considerable amount of information

about each connection.

© Copyright : IT Engg Portal – www.itportal.in 264

What is a DNS resource record?

A resource record is an entry in a name server's database. There are several types of

resource records used, including name-to-address resolution information. Resource

records are maintained as ASCII files.

What is a pseudo tty?

A pseudo tty or false terminal enables external machines to connect through Telnet or

rlogin. Without a pseudo tty, no connection can take place.

What is the Network Time Protocol?

A protocol that assures accurate local timekeeping with reference to radio and atomic

clocks located on the Internet. This protocol is capable of synchronising distributed

clocks within milliseconds over long time periods. It is defined in STD 12, RFC 1119.

What is mesh network?

A network in which there are multiple network links between computers to provide

multiple paths for data to travel.

What is RAID?

A method for providing fault tolerance by using multiple hard disk drives.

What is a Management Information Base (MIB)?

A Management Information Base is part of every SNMP-managed device. Each

SNMP agent has the MIB database that contains information about the device's status,

its performance, connections, and configuration. The MIB is queried by SNMP.

What is cladding?

A layer of a glass surrounding the center fiber of glass inside a fiber-optic cable.

What is subnet?

A generic term for section of a large networks usually separated by a bridge or

router. A gateway operates at the upper levels of the OSI model and translates

information between two completely different network architectures or data formats.

What is point-to-point protocol?

A communications protocol used to connect computers to remote networking services

including Internet service providers.

© Copyright : IT Engg Portal – www.itportal.in 265

What are 10Base2, 10Base5 and 10BaseT Ethernet LANs ?

10Base2—An Ethernet term meaning a maximum transfer rate of 10 Megabits per

second that uses baseband signaling, with a contiguous cable segment length of 100

meters and a maximum of 2 segments

10Base5—An Ethernet term meaning a maximum transfer rate of 10 Megabits per

second that uses baseband signaling, with 5 continuous segments not exceeding 100

meters per segment.

10BaseT—An Ethernet term meaning a maximum transfer rate of 10 Megabits per

second that uses baseband signaling and twisted pair cabling.

What are the possible ways of data exchange?

(i) Simplex

(ii) Half-duplex

(iii) Full-duplex.

What are the two types of transmission technology available?

(i) Broadcast

(ii) point-to-point.

How do I convert a numeric IP address like 192.18.97.39 into a hostname like

java.sun.com?

String hostname = InetAddress.getByName("192.18.97.39").getHostName();

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

© Copyright : IT Engg Portal – www.itportal.in 266

Operating System

Interview Questions

&

Answers

© Copyright : IT Engg Portal – www.itportal.in 267

Operating System Interview Questions and Answers

What's OPERATING SYSTEM?

An Operating System, or OS, is a software program that enables the computer

hardware to communicate and operate with the computer software. Without a

computer Operating System, a computer would be useless.

OPERATING SYSTEM TYPES As computers have progressed and developed so have the types of operating systems.

Below is a basic list of the different types of operating systems and a few examples of

Operating Systems that fall into each of the categories. Many computer Operating

Systems will fall into more than one of the below categories.

GUI - Short for Graphical User Interface, a GUI Operating System contains graphics

and icons and is commonly navigated by using a computer mouse. See our GUI

dictionary definition for a complete definition. Below are some examples of GUI

Operating Systems.

System 7.x

Windows 98

Windows CE

Multi-user - A multi-user Operating System allows for multiple users to use the same

computer at the same time and/or different times. See our multi-user dictionary

definition for a complete definition for a complete definition. Below are some

examples of multi-user Operating Systems.

Linux

Unix

Windows 2000

Windows XP

Mac OS X

Multiprocessing - An Operating System capable of supporting and utilizing more

than one computer processor. Below are some examples of multiprocessing Operating

Systems.

© Copyright : IT Engg Portal – www.itportal.in 268

Linux

Unix

Windows 2000

Windows XP

Mac OS X

Multitasking - An Operating system that is capable of allowing multiple software

processes to run at the same time. Below are some examples of multitasking Operating

Systems.

Unix

Windows 2000

Windows XP

Mac OS X

Multithreading - Operating systems that allow different parts of a software program

to run concurrently. Operating systems that would fall into this category are:

Linux

Unix

Windows 2000

Windows XP

Mac OS X

What are the basic functions of an operating system?

- Operating system controls and coordinates the use of the hardware among the

various applications programs for various uses. Operating system acts as resource

allocator and manager. Since there are many possibly conflicting requests for

resources the operating system must decide which requests are allocated resources to

operating the computer system efficiently and fairly. Also operating system is control

program which controls the user programs to prevent errors and improper use of the

computer. It is especially concerned with the operation and control of I/O devices.

Why paging is used? -Paging is solution to external fragmentation problem which is to permit the logical

© Copyright : IT Engg Portal – www.itportal.in 269

address space of a process to be noncontiguous, thus allowing a process to be

allocating physical memory wherever the latter is available.

While running DOS on a PC, which command would be used to duplicate the

entire diskette? diskcopy

What resources are used when a thread created? How do they differ from those

when a process is created? When a thread is created the threads does not require any new resources to execute the

thread shares the resources like memory of the process to which they belong to. The

benefit of code sharing is that it allows an application to have several different threads

of activity all within the same address space. Whereas if a new process creation is very

heavyweight because it always requires new address space to be created and even if

they share the memory then the inter process communication is expensive when

compared to the communication between the threads.

What is virtual memory? Virtual memory is hardware technique where the system appears to have more

memory that it actually does. This is done by time-sharing, the physical memory and

storage parts of the memory one disk when they are not actively being used.

What is Throughput, Turnaround time, waiting time and Response time? Throughput – number of processes that complete their execution per time unit.

Turnaround time – amount of time to execute a particular process. Waiting time –

amount of time a process has been waiting in the ready queue. Response time –

amount of time it takes from when a request was submitted until the first response is

produced, not output (for time-sharing environment).

What is the state of the processor, when a process is waiting for some event to

occur? Waiting state

What is the important aspect of a real-time system or Mission Critical Systems? A real time operating system has well defined fixed time constraints. Process must be

done within the defined constraints or the system will fail. An example is the operating

system for a flight control computer or an advanced jet airplane. Often used as a

control device in a dedicated application such as controlling scientific experiments,

© Copyright : IT Engg Portal – www.itportal.in 270

medical imaging systems, industrial control systems, and some display systems. Real-

Time systems may be either hard or soft real-time. Hard real-time: Secondary storage

limited or absent, data stored in short term memory, or read-only memory (ROM),

Conflicts with time-sharing systems, not supported by general-purpose operating

systems. Soft real-time: Limited utility in industrial control of robotics, Useful in

applications (multimedia, virtual reality) requiring advanced operating-system

features.

What is the difference between Hard and Soft real-time systems?

- A hard real-time system guarantees that critical tasks complete on time. This goal

requires that all delays in the system be bounded from the retrieval of the stored data

to the time that it takes the operating system to finish any request made of it. A soft

real time system where a critical real-time task gets priority over other tasks and

retains that priority until it completes. As in hard real time systems kernel delays need

to be bounded

What is the cause of thrashing? How does the system detect thrashing?

Once it detects thrashing, what can the system do to eliminate this problem? -

Thrashing is caused by under allocation of the minimum number of pages required by

a process, forcing it to continuously page fault. The system can detect thrashing by

evaluating the level of CPU utilization as compared to the level of multiprogramming.

It can be eliminated by reducing the level of multiprogramming.

What is multi tasking, multi programming, multi threading?

Multi programming: Multiprogramming is the technique of running several programs

at a time using timesharing. It allows a computer to do several things at the same time.

Multiprogramming creates logical parallelism. The concept of multiprogramming is

that the operating system keeps several jobs in memory simultaneously. The operating

system selects a job from the job pool and starts executing a job, when that job needs

to wait for any i/o operations the CPU is switched to another job. So the main idea

here is that the CPU is never idle. Multi tasking: Multitasking is the logical extension

of multiprogramming .The concept of multitasking is quite similar to

multiprogramming but difference is that the switching between jobs occurs so

frequently that the users can interact with each program while it is running. This

concept is also known as time-sharing systems. A time-shared operating system uses

CPU scheduling and multiprogramming to provide each user with a small portion of

time-shared system. Multi threading: An application typically is implemented as a

© Copyright : IT Engg Portal – www.itportal.in 271

separate process with several threads of control. In some situations a single application

may be required to perform several similar tasks for example a web server accepts

client requests for web pages, images, sound, and so forth. A busy web server may

have several of clients concurrently accessing it. If the web server ran as a traditional

single-threaded process, it would be able to service only one client at a time. The

amount of time that a client might have to wait for its request to be serviced could be

enormous. So it is efficient to have one process that contains multiple threads to serve

the same purpose. This approach would multithread the web-server process, the server

would create a separate thread that would listen for client requests when a request was

made rather than creating another process it would create another thread to service the

request. To get the advantages like responsiveness, Resource sharing economy and

utilization of multiprocessor architectures multithreading concept can be used.

What is hard disk and what is its purpose?

Hard disk is the secondary storage device, which holds the data in bulk, and it holds

the data on the magnetic medium of the disk. Hard disks have a hard platter that holds

the magnetic medium, the magnetic medium can be easily erased and rewritten, and a

typical desktop machine will have a hard disk with a capacity of between 10 and 40

gigabytes. Data is stored onto the disk in the form of files.

What is fragmentation? Different types of fragmentation?

- Fragmentation occurs in a dynamic memory allocation system when many of the free

blocks are too small to satisfy any request. External Fragmentation: External

Fragmentation happens when a dynamic memory allocation algorithm allocates some

memory and a small piece is left over that cannot be effectively used. If too much

external fragmentation occurs, the amount of usable memory is drastically reduced.

Total memory space exists to satisfy a request, but it is not contiguous. Internal

Fragmentation: Internal fragmentation is the space wasted inside of allocated memory

blocks because of restriction on the allowed sizes of allocated blocks. Allocated

memory may be slightly larger than requested memory; this size difference is memory

internal to a partition, but not being used

What is DRAM? In which form does it store data?

- DRAM is not the best, but it‘s cheap, does the job, and is available almost

everywhere you look. DRAM data resides in a cell made of a capacitor and a

transistor. The capacitor tends to lose data unless it‘s recharged every couple of

© Copyright : IT Engg Portal – www.itportal.in 272

milliseconds, and this recharging tends to slow down the performance of DRAM

compared to speedier RAM types.

What is Dispatcher?

- Dispatcher module gives control of the CPU to the process selected by the short-term

scheduler; this involves: Switching context, Switching to user mode, Jumping to the

proper location in the user program to restart that program, dispatch latency – time it

takes for the dispatcher to stop one process and start another running.

What is CPU Scheduler?

- Selects from among the processes in memory that are ready to execute, and allocates

the CPU to one of them. CPU scheduling decisions may take place when a process:

1.Switches from running to waiting state. 2.Switches from running to ready state.

3.Switches from waiting to ready. 4.Terminates. Scheduling under 1 and 4 is non-

preemptive. All other scheduling is preemptive.

What is Context Switch?

- Switching the CPU to another process requires saving the state of the old process and

loading the saved state for the new process. This task is known as a context switch.

Context-switch time is pure overhead, because the system does no useful work while

switching. Its speed varies from machine to machine, depending on the memory speed,

the number of registers which must be copied, the existed of special instructions(such

as a single instruction to load or store all registers).

What is cache memory?

- Cache memory is random access memory (RAM) that a computer microprocessor

can access more quickly than it can access regular RAM. As the microprocessor

processes data, it looks first in the cache memory and if it finds the data there (from a

previous reading of data), it does not have to do the more time-consuming reading of

data from larger memory.

What is a Safe State and what is its use in deadlock avoidance?

- When a process requests an available resource, system must decide if immediate

allocation leaves the system in a safe state. System is in safe state if there exists a safe

sequence of all processes. Deadlock Avoidance: ensure that a system will never enter

an unsafe state.

© Copyright : IT Engg Portal – www.itportal.in 273

What is a Real-Time System?

- A real time process is a process that must respond to the events within a certain time

period. A real time operating system is an operating system that can run real time

processes successfully

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

© Copyright : IT Engg Portal – www.itportal.in 274

Linux

Interview Questions

&

Answers

© Copyright : IT Engg Portal – www.itportal.in 275

Linux Interview Questions and Answers

You need to see the last fifteen lines of the files dog, cat and horse. What

command should you use?

Ans :tail -15 dog cat horse

Explanation : The tail utility displays the end of a file. The -15 tells tail to display the

last fifteen lines of each specified file.

Who owns the data dictionary? The SYS user owns the data dictionary. The SYS and SYSTEM users are created

when the database is created.

You routinely compress old log files. You now need to examine a log from two

months ago. In order to view its contents without first having to decompress it,

use the _________ utility. Ans : zcat

Explanation : The zcat utility allows you to examine the contents of a compressed

file much the same way that cat displays a file.

You suspect that you have two commands with the same name as the command is

not producing the expected results. What command can you use to determine the

location of the command being run? Ans :which

Explanation : The which command searches your path until it finds a command that

matches the command you are looking for and displays its full path.

You locate a command in the /bin directory but do not know what it does. What

command can you use to determine its purpose. Ans : whatis

Explanation : The whatis command displays a summary line from the man page for

the specified command.

You wish to create a link to the /data directory in bob's home directory so you

issue the command ln /data /home/bob/datalink but the command fails. What

© Copyright : IT Engg Portal – www.itportal.in 276

option should you use in this command line to be successful.

Ans :Use the -F option

Explanation : In order to create a link to a directory you must use the -F option.

When you issue the command ls -l, the first character of the resulting display

represents the file's ___________. Ans : type

Explanation : The first character of the permission block designates the type of file

that is being displayed.

What utility can you use to show a dynamic listing of running

processes? __________ Ans : top

Explanation : The top utility shows a listing of all running processes that is

dynamically updated.

Where is standard output usually directed?

Ans : to the screen or display

Explanation : By default, your shell directs standard output to your screen or display.

You wish to restore the file memo.ben which was backed up in the tarfile

MyBackup.tar. What command should you type? Ans : tar xf MyBackup.tar memo.ben

Explanation : This command uses the x switch to extract a file. Here the file

memo.ben will be restored from the tarfile MyBackup.tar.

You need to view the contents of the tarfile called MyBackup.tar. What command

would you use?

Ans : tar tf MyBackup.tar

© Copyright : IT Engg Portal – www.itportal.in 277

Explanation : The t switch tells tar to display the contents and the f modifier specifies

which file to examine.

You want to create a compressed backup of the users' home directories. What

utility should you use? Ans :tar

Explanation : You can use the z modifier with tar to compress your archive at the

same time as creating it.

What daemon is responsible for tracking events on your system? Ans :syslogd

The syslogd daemon is responsible for tracking system information and saving it to

specified log files.

You have a file called phonenos that is almost 4,000 lines long. What text filter

can you use to split it into four pieces each 1,000 lines long? Ans :split

The split text filter will divide files into equally sized pieces. The default length of

each piece is 1,000 lines.

You would like to temporarily change your command line editor to be vi. What

command should you type to change it? Ans : set -o vi

The set command is used to assign environment variables. In this case, you are

instructing your shell to assign vi as your command line editor. However, once you log

off and log back in you will return to the previously defined command line editor.

What account is created when you install Linux? Ans : root

Whenever you install Linux, only one user account is created. This is the superuser

account also known as root.

© Copyright : IT Engg Portal – www.itportal.in 278

What command should you use to check the number of files and disk space used

and each user's defined quotas? Ans : repquota

The repquota command is used to get a report on the status of the quotas you have set

including the amount of allocated space and amount of used space.

In order to run fsck on the root partition, the root partition must be mounted as?

Ans : readonly

You cannot run fsck on a partition that is mounted as read-write.

In order to improve your system's security you decide to implement shadow

passwords. What command should you use? Ans : pwconv

The pwconv command creates the file /etc/shadow and changes all passwords to 'x' in

the /etc/passwd file.

Bob Armstrong, who has a username of boba, calls to tell you he forgot his

password. What command should you use to reset his command? passwd boba

The passwd command is used to change your password. If you do not specify a

username, your password will be changed.

The top utility can be used to change the priority of a running process? Another

utility that can also be used to change priority is ___________? nice

Both the top and nice utilities provide the capability to change the priority of a running

process.

What command should you type to see all the files with an extension of 'mem'

listed in reverse alphabetical order in the /home/ben/memos directory. ls -r /home/ben/memos/*.mem

© Copyright : IT Engg Portal – www.itportal.in 279

The -c option used with ls results in the files being listed in chronological order. You

can use wildcards with the ls command to specify a pattern of filenames.

What file defines the levels of messages written to system log files? kernel.h

To determine the various levels of messages that are defined on your system, examine

the kernel.h file.

What command is used to remove the password assigned to a group? gpasswd -r

The gpasswd command is used to change the password assigned to a group. Use the -r

option to remove the password from the group.

What command would you type to use the cpio to create a backup called

backup.cpio of all the users' home directories? find /home | cpio -o > backup.cpio

The find command is used to create a list of the files and directories contained in

home. This list is then piped to the cpio utility as a list of files to include and the

output is saved to a file called backup.cpio.

What can you type at a command line to determine which shell you are using? echo $SHELL

The name and path to the shell you are using is saved to the SHELL environment

variable. You can then use the echo command to print out the value of any variable by

preceding the variable's name with $. Therefore, typing echo $SHELL will display the

name of your shell.

What type of local file server can you use to provide the distribution installation

materials to the new machine during a network installation?

A) Inetd

B) FSSTND

C) DNS

D) NNTP

E) NFS

© Copyright : IT Engg Portal – www.itportal.in 280

E - You can use an NFS server to provide the distribution installation materials to the

machine on which you are performing the installation. Answers a, b, c, and d are all

valid items but none of them are file servers. Inetd is the superdaemon which controls

all intermittently used network services. The FSSTND is the Linux File System

Standard. DNS provides domain name resolution, and NNTP is the transfer protocol

for usenet news.

If you type the command cat dog & > cat what would you see on your

display? Choose one:

a. Any error messages only.

b. The contents of the file dog.

c. The contents of the file dog and any error messages.

d. Nothing as all output is saved to the file cat.

d

When you use & > for redirection, it redirects both the standard output and standard

error. The output would be saved to the file cat.

You are covering for another system administrator and one of the users asks you

to restore a file for him. You locate the correct tarfile by checking the backup log

but do not know how the directory structure was stored. What command can you

use to determine this?

Choose one:

a. tar fx tarfile dirname

b. tar tvf tarfile filename

c. tar ctf tarfile

d. tar tvf tarfile

d

The t switch will list the files contained in the tarfile. Using the v modifier will display

the stored directory structure.

You have the /var directory on its own partition. You have run out of space.

What should you do? Choose one:

a. Reconfigure your system to not write to the log files.

© Copyright : IT Engg Portal – www.itportal.in 281

b. Use fips to enlarge the partition.

c. Delete all the log files.

d. Delete the partition and recreate it with a larger size.

d

The only way to enlarge a partition is to delete it and recreate it. You will then have to

restore the necessary files from backup.

You have a new application on a CD-ROM that you wish to install. What should

your first step be?

Choose one:

a. Read the installation instructions on the CD-ROM.

b. Use the mount command to mount your CD-ROM as read-write.

c. Use the umount command to access your CD-ROM.

d. Use the mount command to mount your CD-ROM as read-only.

d

Before you can read any of the files contained on the CD-ROM, you must first mount

the CD-ROM.

When you create a new partition, you need to designate its size by defining the

starting and ending _____________. cylinders

When creating a new partition you must first specify its starting cylinder. You can

then either specify its size or the ending cylinder.

What key combination can you press to suspend a running job and place it in the

background?

ctrl-z

Using ctrl-z will suspend a job and put it in the background.

The easiest, most basic form of backing up a file is to _____ it to another

location. copy

© Copyright : IT Engg Portal – www.itportal.in 282

The easiest most basic form of backing up a file is to make a copy of that file to

another location such as a floppy disk.

What type of server is used to remotely assign IP addresses to machines during

the installation process?

A) SMB

B) NFS

C) DHCP

D) FT

E) HTTP

C - You can use a DHCP server to assign IP addresses to individual machines during

the installation process. Answers a, b, d, and e list legitimate Linux servers, but these

servers do not provide IP addresses. The SMB, or Samba, tool is used for file and print

sharing across multi-OS networks. An NFS server is for file sharing across Linux net-

works. FTP is a file storage server that allows people to browse and retrieve

information by logging in to it, and HTTP is for the Web.

Which password package should you install to ensure that the central password

file couldn't be stolen easily?

A) PAM

B) tcp_wrappers

C) shadow

D) securepass

E) ssh

C - The shadow password package moves the central password file to a more secure

location. Answers a, b, and e all point to valid packages, but none of these places the

password file in a more secure location. Answer d points to an invalid package.

When using useradd to create a new user account, which of the following tasks is

not done automatically.

Choose one:

a. Assign a UID.

b. Assign a default shell.

c. Create the user's home directory.

© Copyright : IT Engg Portal – www.itportal.in 283

d. Define the user's home directory.

c

The useradd command will use the system default for the user's home directory. The

home directory is not created, however, unless you use the -m option.

You want to enter a series of commands from the command-line. What would be

the quickest way to do this?

Choose One

a. Press enter after entering each command and its arguments

b. Put them in a script and execute the script

c. Separate each command with a semi-colon (;) and press enter after the last

command

d. Separate each command with a / and press enter after the last command

c

The semi-colon may be used to tell the shell that you are entering multiple commands

that should be executed serially. If these were commands that you would frequently

want to run, then a script might be more efficient. However, to run these commands

only once, enter the commands directly at the command line.

You attempt to use shadow passwords but are unsuccessful. What characteristic

of the /etc/passwd file may cause this?

Choose one:

a. The login command is missing.

b. The username is too long.

c. The password field is blank.

d. The password field is prefaced by an asterisk.

c

The password field must not be blank before converting to shadow passwords.

When you install a new application, documentation on that application is also

usually installed. Where would you look for the documentation after installing an

© Copyright : IT Engg Portal – www.itportal.in 284

application called MyApp?

Choose one:

a. /usr/MyApp

b. /lib/doc/MyApp

c. /usr/doc/MyApp

d. In the same directory where the application is installed.

c

The default location for application documentation is in a directory named for the

application in the /usr/doc directory.

What file would you edit in your home directory to change which window

manager you want to use?

A) Xinit

B) .xinitrc

C) XF86Setup

D) xstart

E) xf86init

Answer: B - The ~/.xinitrc file allows you to set which window man-ager you want to

use when logging in to X from that account.

Answers a, d, and e are all invalid files. Answer c is the main X server configuration

file.

What command allows you to set a processor-intensive job to use less CPU time?

A) ps

B) nice

C) chps

D) less

E) more

Answer: B - The nice command is used to change a job's priority level, so that it runs

slower or faster. Answers a, d, and e are valid commands but are not used to change

process information. Answer c is an invalid command.

© Copyright : IT Engg Portal – www.itportal.in 285

While logged on as a regular user, your boss calls up and wants you to create a

new user account immediately. How can you do this without first having to close

your work, log off and logon as root?

Choose one:

a. Issue the command rootlog.

b. Issue the command su and type exit when finished.

c. Issue the command su and type logoff when finished.

d. Issue the command logon root and type exit when finished.

Answer: b

You can use the su command to imitate any user including root. You will be prompted

for the password for the root account. Once you have provided it you are logged in as

root and can do any administrative duties.

There are seven fields in the /etc/passwd file. Which of the following lists all the

fields in the correct order?

Choose one:

a. username, UID, GID, home directory, command, comment

b. username, UID, GID, comment, home directory, command

c. UID, username, GID, home directory, comment, command

d. username, UID, group name, GID, home directory, comment

Answer: b

The seven fields required for each line in the /etc/passwd file are username, UID, GID,

comment, home directory, command. Each of these fields must be separated by a

colon even if they are empty.

Which of the following commands will show a list of the files in your home

directory including hidden files and the contents of all subdirectories?

Choose one:

a. ls -c home

b. ls -aR /home/username

c. ls -aF /home/username

d. ls -l /home/username

Answer: b

The ls command is used to display a listing of files. The -a option will cause hidden

© Copyright : IT Engg Portal – www.itportal.in 286

files to be displayed as well. The -R option causes ls to recurse down the directory

tree. All of this starts at your home directory.

In order to prevent a user from logging in, you can add a(n) ________at the

beginning of the password field. Answer: asterick

If you add an asterick at the beginning of the password field in the /etc/passwd file,

that user will not be able to log in.

You have a directory called /home/ben/memos and want to move it to

/home/bob/memos so you issue the command mv /home/ben/memos /home/bob.

What is the results of this action?

Choose one:

a. The files contained in /home/ben/memos are moved to the directory

/home/bob/memos/memos.

b. The files contained in /home/ben/memos are moved to the directory

/home/bob/memos.

c. The files contained in /home/ben/memos are moved to the directory

/home/bob/.

d. The command fails since a directory called memos already exists in the target

directory.

Answer: a

When using the mv command to move a directory, if a directory of the same name

exists then a subdirectory is created for the files to be moved.

Which of the following tasks is not necessary when creating a new user by editing

the /etc/passwd file?

Choose one:

a. Create a link from the user's home directory to the shell the user will use.

b. Create the user's home directory

c. Use the passwd command to assign a password to the account.

d. Add the user to the specified group.

Answer: a

© Copyright : IT Engg Portal – www.itportal.in 287

There is no need to link the user's home directory to the shell command. Rather, the

specified shell must be present on your system.

You issue the following command useradd -m bobm But the user cannot logon.

What is the problem?

Choose one:

a. You need to assign a password to bobm's account using the passwd command.

b. You need to create bobm's home directory and set the appropriate

permissions.

c. You need to edit the /etc/passwd file and assign a shell for bobm's account.

d. The username must be at least five characters long.

Answer: a

The useradd command does not assign a password to newly created accounts. You will

still need to use the passwd command to assign a password.

You wish to print the file vacations with 60 lines to a page. Which of the following

commands will accomplish this? Choose one:

a. pr -l60 vacations | lpr

b. pr -f vacations | lpr

c. pr -m vacations | lpr

d. pr -l vacations | lpr

Answer: a

The default page length when using pr is 66 lines. The -l option is used to specify a

different length.

Which file defines all users on your system?

Choose one:

a. /etc/passwd

b. /etc/users

c. /etc/password

d. /etc/user.conf

Answer: a

The /etc/passwd file contains all the information on users who may log into your

system. If a user account is not contained in this file, then the user cannot log in.

© Copyright : IT Engg Portal – www.itportal.in 288

Which two commands can you use to delete directories?

A) rm

B) rm -rf

C) rmdir

D) rd

E) rd -rf

Answer(s): B, C - You can use rmdir or rm -rf to delete a directory. Answer a is

incorrect, because the rm command without any specific flags will not delete a

directory, it will only delete files. Answers d and e point to a non-existent command.

Which partitioning tool is available in all distributions?

A) Disk Druid

B) fdisk

C) Partition Magic

D) FAT32

E) System Commander

Answer(s): B - The fdisk partitioning tool is available in all Linux distributions.

Answers a, c, and e all handle partitioning, but do not come with all distributions. Disk

Druid is made by Red Hat and used in its distribution along with some derivatives.

Partition Magic and System Commander are tools made by third-party companies.

Answer d is not a tool, but a file system type. Specifically, FAT32 is the file system

type used in Windows 98.

Which partitions might you create on the mail server's hard drive(s) other than

the root, swap, and boot partitions?

[Choose all correct answers]

A) /var/spool

B) /tmp

C) /proc

D) /bin

E) /home

Answer(s): A, B, E - Separating /var/spool onto its own partition helps to ensure that if

something goes wrong with the mail server or spool, the output cannot overrun the file

system. Putting /tmp on its own partition prevents either software or user items in the

© Copyright : IT Engg Portal – www.itportal.in 289

/tmp directory from overrunning the file system. Placing /home off on its own is

mostly useful for system re-installs or upgrades, allowing you to not have to wipe the

/home hierarchy along with other areas. Answers c and d are not possible, as the /proc

portion of the file system is virtual-held in RAM-not placed on the hard drives, and the

/bin hierarchy is necessary for basic system functionality and, therefore, not one that

you can place on a different partition.

When planning your backup strategy you need to consider how often you will

perform a backup, how much time the backup takes and what media you will use.

What other factor must you consider when planning your backup

strategy? _________

what to backup

Choosing which files to backup is the first step in planning your backup strategy.

What utility can you use to automate rotation of logs? Answer: logrotate

The logrotate command can be used to automate the rotation of various logs.

In order to display the last five commands you have entered using the history

command, you would type ___________ .

Answer: history 5

The history command displays the commands you have previously entered. By passing

it an argument of 5, only the last five commands will be displayed.

What command can you use to review boot messages? Answer: dmesg

The dmesg command displays the system messages contained in the kernel ring

buffer. By using this command immediately after booting your computer, you will see

the boot messages.

What is the minimum number of partitions you need to install Linux? Answer: 2

Linux can be installed on two partitions, one as / which will contain all files and a

swap partition.

© Copyright : IT Engg Portal – www.itportal.in 290

What is the name and path of the main system log? Answer: /var/log/messages

By default, the main system log is /var/log/messages.

Of the following technologies, which is considered a client-side script?

A) JavaScript

B) Java

C) ASP

D) C++

Answer: A - JavaScript is the only client-side script listed. Java and C++ are complete

programming languages. Active Server Pages are parsed on the server with the results

being sent to the client in HTML

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

© Copyright : IT Engg Portal – www.itportal.in 291

Unix

Interview Questions &

Answers

© Copyright : IT Engg Portal – www.itportal.in 292

Unix Interview Questions and Answers

How are devices represented in UNIX?

All devices are represented by files called special files that are located in/dev

directory. Thus, device files and other files are named and accessed in the same way.

A 'regular file' is just an ordinary data file in the disk. A 'block special file' represents a

device with characteristics similar to a disk (data transfer in terms of blocks). A

'character special file' represents a device with characteristics similar to a keyboard

(data transfer is by stream of bits in sequential order).

What is 'inode'? All UNIX files have its description stored in a structure called 'inode'. The inode

contains info about the file-size, its location, time of last access, time of last

modification, permission and so on. Directories are also represented as files and have

an associated inode. In addition to descriptions about the file, the inode contains

pointers to the data blocks of the file. If the file is large, inode has indirect pointer to a

block of pointers to additional data blocks (this further aggregates for larger files). A

block is typically 8k.

Inode consists of the following fields:

File owner identifier

File type

File access permissions

File access times

Number of links

File size

Location of the file data

Brief about the directory representation in UNIX A Unix directory is a file containing a correspondence between filenames and inodes.

A directory is a special file that the kernel maintains. Only kernel modifies directories,

but processes can read directories. The contents of a directory are a list of filename

and inode number pairs. When new directories are created, kernel makes two entries

named '.' (refers to the directory itself) and '..' (refers to parent directory).

System call for creating directory is mkdir (pathname, mode).

What are the Unix system calls for I/O? open(pathname,flag,mode) - open file

creat(pathname,mode) - create file

© Copyright : IT Engg Portal – www.itportal.in 293

close(filedes) - close an open file

read(filedes,buffer,bytes) - read data from an open file

write(filedes,buffer,bytes) - write data to an open file

lseek(filedes,offset,from) - position an open file

dup(filedes) - duplicate an existing file descriptor

dup2(oldfd,newfd) - duplicate to a desired file descriptor

fcntl(filedes,cmd,arg) - change properties of an open file

ioctl(filedes,request,arg) - change the behaviour of an open file

The difference between fcntl anf ioctl is that the former is intended for any open file,

while the latter is for device-specific operations.

How do you change File Access Permissions?

Every file has following attributes:

owner's user ID ( 16 bit integer )

owner's group ID ( 16 bit integer )

File access mode word

'r w x -r w x- r w x'

(user permission-group permission-others permission)

r-read, w-write, x-execute

To change the access mode, we use chmod(filename,mode).

Example 1:

To change mode of myfile to 'rw-rw-r--' (ie. read, write permission for user -

read,write permission for group - only read permission for others) we give the args as:

chmod(myfile,0664) .

Each operation is represented by discrete values

'r' is 4

'w' is 2

'x' is 1

Therefore, for 'rw' the value is 6(4+2).

Example 2:

To change mode of myfile to 'rwxr--r--' we give the args as:

chmod(myfile,0744).

What are links and symbolic links in UNIX file system? A link is a second name (not a file) for a file. Links can be used to assign more than

one name to a file, but cannot be used to assign a directory more than one name or link

© Copyright : IT Engg Portal – www.itportal.in 294

filenames on different computers.

Symbolic link 'is' a file that only contains the name of another file.Operation on the

symbolic link is directed to the file pointed by the it.Both the limitations of links are

eliminated in symbolic links.

Commands for linking files are:

Link ln filename1 filename2

Symbolic link ln -s filename1 filename2

What is a FIFO? FIFO are otherwise called as 'named pipes'. FIFO (first-in-first-out) is a special file

which is said to be data transient. Once data is read from named pipe, it cannot be read

again. Also, data can be read only in the order written. It is used in interprocess

communication where a process writes to one end of the pipe (producer) and the other

reads from the other end (consumer).

How do you create special files like named pipes and device files? The system call mknod creates special files in the following sequence.

1. kernel assigns new inode,

2. sets the file type to indicate that the file is a pipe, directory or special file,

3. If it is a device file, it makes the other entries like major, minor device numbers.

For example:

If the device is a disk, major device number refers to the disk controller and minor

device number is the disk.

Discuss the mount and unmount system calls The privileged mount system call is used to attach a file system to a directory of

another file system; the unmount system call detaches a file system. When you mount

another file system on to your directory, you are essentially splicing one directory tree

onto a branch in another directory tree. The first argument to mount call is the mount

point, that is , a directory in the current file naming system. The second argument is

the file system to mount to that point. When you insert a cdrom to your unix system's

drive, the file system in the cdrom automatically mounts to /dev/cdrom in your system.

How does the inode map to data block of a file? Inode has 13 block addresses. The first 10 are direct block addresses of the first 10

data blocks in the file. The 11th address points to a one-level index block. The 12th

address points to a two-level (double in-direction) index block. The 13th address

points to a three-level(triple in-direction)index block. This provides a very large

© Copyright : IT Engg Portal – www.itportal.in 295

maximum file size with efficient access to large files, but also small files are accessed

directly in one disk read.

What is a shell?

A shell is an interactive user interface to an operating system services that allows an

user to enter commands as character strings or through a graphical user interface. The

shell converts them to system calls to the OS or forks off a process to execute the

command. System call results and other information from the OS are presented to the

user through an interactive interface. Commonly used shells are sh,csh,ks etc.

Brief about the initial process sequence while the system boots up. While booting, special process called the 'swapper' or 'scheduler' is created with

Process-ID 0. The swapper manages memory allocation for processes and influences

CPU allocation. The swapper inturn creates 3 children:

the process dispatcher,

vhand and

dbflush

with IDs 1,2 and 3 respectively.

This is done by executing the file /etc/init. Process dispatcher gives birth to the shell.

Unix keeps track of all the processes in an internal data structure called the Process

Table (listing command is ps -el).

What are various IDs associated with a process? Unix identifies each process with a unique integer called ProcessID. The process that

executes the request for creation of a process is called the 'parent process' whose PID

is 'Parent Process ID'. Every process is associated with a particular user called the

'owner' who has privileges over the process. The identification for the user is 'UserID'.

Owner is the user who executes the process. Process also has 'Effective User ID' which

determines the access privileges for accessing resources like files.

getpid() -process id

getppid() -parent process id

getuid() -user id

geteuid() -effective user id

Explain fork() system call. The `fork()' used to create a new process from an existing process. The new process is

called the child process, and the existing process is called the parent. We can tell

© Copyright : IT Engg Portal – www.itportal.in 296

which is which by checking the return value from `fork()'. The parent gets the child's

pid returned to him, but the child gets 0 returned to him.

Predict the output of the following program code

main()

{

fork();

printf("Hello World!");

}

Answer:

Hello World!Hello World!

Explanation:

The fork creates a child that is a duplicate of the parent process. The child begins from

the fork().All the statements after the call to fork() will be executed twice.(once by the

parent process and other by child). The statement before fork() is executed only by the

parent process.

Predict the output of the following program code

main()

{

fork(); fork(); fork();

printf("Hello World!");

}

Answer:

"Hello World" will be printed 8 times.

Explanation:

2^n times where n is the number of calls to fork()

List the system calls used for process management: System calls Description

fork() To create a new process

exec() To execute a new program in a process

wait() To wait until a created process completes its execution

exit() To exit from a process execution

getpid() To get a process identifier of the current process

getppid() To get parent process identifier

© Copyright : IT Engg Portal – www.itportal.in 297

nice() To bias the existing priority of a process

brk() To increase/decrease the data segment size of a process

How can you get/set an environment variable from a program?: Getting the value of an environment variable is done by using `getenv()'. Setting the

value of an environment variable is done by using `putenv()'.

How can a parent and child process communicate? A parent and child can communicate through any of the normal inter-process

communication schemes (pipes, sockets, message queues, shared memory), but also

have some special ways to communicate that take advantage of their relationship as a

parent and child. One of the most obvious is that the parent can get the exit status of

the child.

What is a zombie? When a program forks and the child finishes before the parent, the kernel still keeps

some of its information about the child in case the parent might need it - for example,

the parent may need to check the child's exit status. To be able to get this information,

the parent calls `wait()'; In the interval between the child terminating and the parent

calling `wait()', the child is said to be a `zombie' (If you do `ps', the child will have a

`Z' in its status field to indicate this.)

What are the process states in Unix? As a process executes it changes state according to its circumstances. Unix processes

have the following states:

Running : The process is either running or it is ready to run .

Waiting : The process is waiting for an event or for a resource.

Stopped : The process has been stopped, usually by receiving a signal.

Zombie : The process is dead but have not been removed from the process table.

What Happens when you execute a program?

When you execute a program on your UNIX system, the system creates a special

environment for that program. This environment contains everything needed for the

system to run the program as if no other program were running on the system. Each

process has process context, which is everything that is unique about the state of the

program you are currently running. Every time you execute a program the UNIX

system does a fork, which performs a series of operations to create a process context

and then execute your program in that context. The steps include the following:

© Copyright : IT Engg Portal – www.itportal.in 298

Allocate a slot in the process table, a list of currently running programs kept by UNIX.

Assign a unique process identifier (PID) to the process.

iCopy the context of the parent, the process that requested the spawning of the new

process.

Return the new PID to the parent process. This enables the parent process to examine

or control the process directly. After the fork is complete, UNIX runs your program.

What Happens when you execute a command? When you enter 'ls' command to look at the contents of your current working

directory, UNIX does a series of things to create an environment for ls and the run it:

The shell has UNIX perform a fork. This creates a new process that the shell will use

to run the ls program. The shell has UNIX perform an exec of the ls program. This

replaces the shell program and data with the program and data for ls and then starts

running that new program. The ls program is loaded into the new process context,

replacing the text and data of the shell. The ls program performs its task, listing the

contents of the current directory.

What is a Daemon? A daemon is a process that detaches itself from the terminal and runs, disconnected, in

the background, waiting for requests and responding to them. It can also be defined as

the background process that does not belong to a terminal session. Many system

functions are commonly performed by daemons, including the sendmail daemon,

which handles mail, and the NNTP daemon, which handles USENET news. Many

other daemons may exist. Some of the most common daemons are:

init: Takes over the basic running of the system when the kernel has finished the boot

process.

inetd: Responsible for starting network services that do not have their own stand-alone

daemons. For example, inetd usually takes care of incoming rlogin, telnet, and ftp

connections.

cron: Responsible for running repetitive tasks on a regular schedule.

What is 'ps' command for? The ps command prints the process status for some or all of the running processes. The

information given are the process identification number (PID),the amount of time that

the process has taken to execute so far etc.

© Copyright : IT Engg Portal – www.itportal.in 299

How would you kill a process? The kill command takes the PID as one argument; this identifies which process to

terminate. The PID of a process can be got using 'ps' command.

What is an advantage of executing a process in background? The most common reason to put a process in the background is to allow you to do

something else interactively without waiting for the process to complete. At the end of

the command you add the special background symbol, &. This symbol tells your shell

to execute the given command in the background.

Example: cp *.* ../backup& (cp is for copy)

How do you execute one program from within another? The system calls used for low-level process creation are execlp() and execvp(). The

execlp call overlays the existing program with the new one , runs that and exits. The

original program gets back control only when an error occurs.

execlp(path,file_name,arguments..); //last argument must be NULL A variant of

execlp called execvp is used when the number of arguments is not known in advance.

execvp(path,argument_array); //argument array should be terminated by NULL

What is IPC? What are the various schemes available? The term IPC (Inter-Process Communication) describes various ways by which

different process running on some operating system communicate between each other.

Various schemes available are as follows: Pipes:

One-way communication scheme through which different process can communicate.

The problem is that the two processes should have a common ancestor (parent-child

relationship). However this problem was fixed with the introduction of named-pipes

(FIFO).

Message Queues :

Message queues can be used between related and unrelated processes running on a

machine.

Shared Memory:

This is the fastest of all IPC schemes. The memory to be shared is mapped into the

address space of the processes (that are sharing). The speed achieved is attributed to

the fact that there is no kernel involvement. But this scheme needs synchronization.

Various forms of synchronisation are mutexes, condition-variables, read-write locks,

record-locks, and semaphores.

© Copyright : IT Engg Portal – www.itportal.in 300

What is the difference between Swapping and Paging? Swapping: Whole process is moved from the swap device to the main memory for

execution. Process size must be less than or equal to the available main memory. It is

easier to implementation and overhead to the system. Swapping systems does not

handle the memory more flexibly as compared to the paging systems.

Paging:

Only the required memory pages are moved to main memory from the swap device for

execution. Process size does not matter. Gives the concept of the virtual memory.

It provides greater flexibility in mapping the virtual address space into the physical

memory of the machine. Allows more number of processes to fit in the main memory

simultaneously. Allows the greater process size than the available physical memory.

Demand paging systems handle the memory more flexibly.

What is major difference between the Historic Unix and the new BSD release of

Unix System V in terms of Memory Management? Historic Unix uses Swapping – entire process is transferred to the main memory from

the swap device, whereas the Unix System V uses Demand Paging – only the part of

the process is moved to the main memory. Historic Unix uses one Swap Device and

Unix System V allow multiple Swap Devices.

What is the main goal of the Memory Management?

It decides which process should reside in the main memory, Manages the parts of the

virtual address space of a process which is non-core resident, Monitors the available

main memory and periodically write the processes into the swap device to provide

more processes fit in the main memory simultaneously.

What is a Map? A Map is an Array, which contains the addresses of the free space in the swap device

that are allocatable resources, and the number of the resource units available there.

This allows First-Fit allocation of contiguous blocks of a resource. Initially the Map

contains one entry – address (block offset from the starting of the swap area) and the

total number of resources. Kernel treats each unit of Map as a group of disk blocks. On

the allocation and freeing of the resources Kernel updates the Map for accurate

information.

What scheme does the Kernel in Unix System V follow while choosing a swap

device among the multiple swap devices?

© Copyright : IT Engg Portal – www.itportal.in 301

Kernel follows Round Robin scheme choosing a swap device among the multiple

swap devices in Unix System V.

What is a Region? A Region is a continuous area of a process‘s address space (such as text, data and

stack). The kernel in a ‗Region Table‘ that is local to the process maintains region.

Regions are sharable among the process.

What are the events done by the Kernel after a process is being swapped out

from the main memory? When Kernel swaps the process out of the primary memory, it performs the following:

Kernel decrements the Reference Count of each region of the process. If the reference

count becomes zero, swaps the region out of the main memory,

Kernel allocates the space for the swapping process in the swap device,

Kernel locks the other swapping process while the current swapping operation is going

on,

The Kernel saves the swap address of the region in the region table.

Is the Process before and after the swap are the same? Give reason. Process before swapping is residing in the primary memory in its original form. The

regions (text, data and stack) may not be occupied fully by the process, there may be

few empty slots in any of the regions and while swapping Kernel do not bother about

the empty slots while swapping the process out. After swapping the process resides in

the swap (secondary memory) device. The regions swapped out will be present but

only the occupied region slots but not the empty slots that were present before

assigning. While swapping the process once again into the main memory, the Kernel

referring to the Process Memory Map, it assigns the main memory accordingly taking

care of the empty slots in the regions.

What do you mean by u-area (user area) or u-block? This contains the private data that is manipulated only by the Kernel. This is local to

the Process, i.e. each process is allocated a u-area.

What are the entities that are swapped out of the main memory while swapping

the process out of the main memory? All memory space occupied by the process, process‘s u-area, and Kernel stack are

swapped out, theoretically. Practically, if the process‘s u-area contains the Address

© Copyright : IT Engg Portal – www.itportal.in 302

Translation Tables for the process then Kernel implementations do not swap the u-

area.

What is Fork swap?

fork() is a system call to create a child process. When the parent process calls fork()

system call, the child process is created and if there is short of memory then the child

process is sent to the read-to-run state in the swap device, and return to the user state

without swapping the parent process. When the memory will be available the child

process will be swapped into the main memory.

What is Expansion swap? At the time when any process requires more memory than it is currently allocated, the

Kernel performs Expansion swap. To do this Kernel reserves enough space in the

swap device. Then the address translation mapping is adjusted for the new virtual

address space but the physical memory is not allocated. At last Kernel swaps the

process into the assigned space in the swap device. Later when the Kernel swaps the

process into the main memory this assigns memory according to the new address

translation mapping.

How the Swapper works? The swapper is the only process that swaps the processes. The Swapper operates only

in the Kernel mode and it does not uses System calls instead it uses internal Kernel

functions for swapping. It is the archetype of all kernel process.

What are the processes that are not bothered by the swapper? Give Reason.

Zombie process: They do not take any up physical memory.

Processes locked in memories that are updating the region of the process.

Kernel swaps only the sleeping processes rather than the ‗ready-to-run‘ processes, as

they have the higher probability of being scheduled than the Sleeping processes.

What are the requirements for a swapper to work? The swapper works on the highest scheduling priority. Firstly it will look for any

sleeping process, if not found then it will look for the ready-to-run process for

swapping. But the major requirement for the swapper to work the ready-to-run process

must be core-resident for at least 2 seconds before swapping out. And for swapping in

the process must have been resided in the swap device for at least 2 seconds. If the

requirement is not satisfied then the swapper will go into the wait state on that event

and it is awaken once in a second by the Kernel.

© Copyright : IT Engg Portal – www.itportal.in 303

What are the criteria for choosing a process for swapping into memory from the

swap device?

The resident time of the processes in the swap device, the priority of the processes and

the amount of time the processes had been swapped out.

What are the criteria for choosing a process for swapping out of the memory to

the swap device?

The process‘s memory resident time,

Priority of the process and

The nice value.

What do you mean by nice value? Nice value is the value that controls {increments or decrements} the priority of the

process. This value that is returned by the nice () system call. The equation for using

nice value is: Priority = (―recent CPU usage‖/constant) + (base- priority) + (nice

value) Only the administrator can supply the nice value. The nice () system call works

for the running process only. Nice value of one process cannot affect the nice value of

the other process.

What are conditions on which deadlock can occur while swapping the processes? All processes in the main memory are asleep.

All ‗ready-to-run‘ processes are swapped out.

There is no space in the swap device for the new incoming process that are swapped

out of the main memory.

There is no space in the main memory for the new incoming process.

What are conditions for a machine to support Demand Paging? Memory architecture must based on Pages,

The machine must support the ‗restartable‘ instructions.

What is „the principle of locality‟?

It‘s the nature of the processes that they refer only to the small subset of the total data

space of the process. i.e. the process frequently calls the same subroutines or executes

the loop instructions.

What is the working set of a process? The set of pages that are referred by the process in the last ‗n‘, references, where ‗n‘ is

called the window of the working set of the process.

© Copyright : IT Engg Portal – www.itportal.in 304

What is the window of the working set of a process? The window of the working set of a process is the total number in which the process

had referred the set of pages in the working set of the process.

What is called a page fault? Page fault is referred to the situation when the process addresses a page in the working

set of the process but the process fails to locate the page in the working set. And on a

page fault the kernel updates the working set by reading the page from the secondary

device.

What are data structures that are used for Demand Paging? Kernel contains 4 data structures for Demand paging. They are,

Page table entries,

Disk block descriptors,

Page frame data table (pfdata),

Swap-use table.

What are the bits that support the demand paging?

Valid, Reference, Modify, Copy on write, Age. These bits are the part of the page

table entry, which includes physical address of the page and protection bits.

Page address

Age

Copy on write

Modify

Reference

Valid

Protection

How the Kernel handles the fork() system call in traditional Unix and in the

System V Unix, while swapping? Kernel in traditional Unix, makes the duplicate copy of the parent‘s address space and

attaches it to the child‘s process, while swapping. Kernel in System V Unix,

manipulates the region tables, page table, and pfdata table entries, by incrementing the

reference count of the region table of shared regions.

Difference between the fork() and vfork() system call? During the fork() system call the Kernel makes a copy of the parent process‘s address

space and attaches it to the child process. But the vfork() system call do not makes any

© Copyright : IT Engg Portal – www.itportal.in 305

copy of the parent‘s address space, so it is faster than the fork() system call. The child

process as a result of the vfork() system call executes exec() system call. The child

process from vfork() system call executes in the parent‘s address space (this can

overwrite the parent‘s data and stack ) which suspends the parent process until the

child process exits.

What is BSS(Block Started by Symbol)? A data representation at the machine level, that has initial values when a program

starts and tells about how much space the kernel allocates for the un-initialized data.

Kernel initializes it to zero at run-time.

What is Page-Stealer process? This is the Kernel process that makes rooms for the incoming pages, by swapping the

memory pages that are not the part of the working set of a process. Page-Stealer is

created by the Kernel at the system initialization and invokes it throughout the lifetime

of the system. Kernel locks a region when a process faults on a page in the region, so

that page stealer cannot steal the page, which is being faulted in.

Name two paging states for a page in memory? The two paging states are:

The page is aging and is not yet eligible for swapping,

The page is eligible for swapping but not yet eligible for reassignment to other virtual

address space.

What are the phases of swapping a page from the memory? Page stealer finds the page eligible for swapping and places the page number in the list

of pages to be swapped. Kernel copies the page to a swap device when necessary and

clears the valid bit in the page table entry, decrements the pfdata reference count, and

places the pfdata table entry at the end of the free list if its reference count is 0.

What is page fault? Its types? Page fault refers to the situation of not having a page in the main memory when any

process references it. There are two types of page fault :

Validity fault,

Protection fault.

In what way the Fault Handlers and the Interrupt handlers are different?

Fault handlers are also an interrupt handler with an exception that the interrupt

© Copyright : IT Engg Portal – www.itportal.in 306

handlers cannot sleep. Fault handlers sleep in the context of the process that caused the

memory fault. The fault refers to the running process and no arbitrary processes are

put to sleep.

What is validity fault?

If a process referring a page in the main memory whose valid bit is not set, it results in

validity fault. The valid bit is not set for those pages:

that are outside the virtual address space of a process,

that are the part of the virtual address space of the process but no physical address is

assigned to it.

What does the swapping system do if it identifies the illegal page for swapping?

If the disk block descriptor does not contain any record of the faulted page, then this

causes the attempted memory reference is invalid and the kernel sends a

―Segmentation violation‖ signal to the offending process. This happens when the

swapping system identifies any invalid memory reference.

What are states that the page can be in, after causing a page fault?

On a swap device and not in memory,

On the free page list in the main memory,

In an executable file,

Marked ―demand zero‖,

Marked ―demand fill‖.

In what way the validity fault handler concludes? It sets the valid bit of the page by clearing the modify bit.

It recalculates the process priority.

At what mode the fault handler executes? At the Kernel Mode.

What do you mean by the protection fault?

Protection fault refers to the process accessing the pages, which do not have the access

permission. A process also incur the protection fault when it attempts to write a page

whose copy on write bit was set during the fork() system call.

How the Kernel handles the copy on write bit of a page, when the bit is set? In situations like, where the copy on write bit of a page is set and that page is shared

© Copyright : IT Engg Portal – www.itportal.in 307

by more than one process, the Kernel allocates new page and copies the content to the

new page and the other processes retain their references to the old page. After copying

the Kernel updates the page table entry with the new page number. Then Kernel

decrements the reference count of the old pfdata table entry. In cases like, where the

copy on write bit is set and no processes are sharing the page, the Kernel allows the

physical page to be reused by the processes. By doing so, it clears the copy on write

bit and disassociates the page from its disk copy (if one exists), because other process

may share the disk copy. Then it removes the pfdata table entry from the page-queue

as the new copy of the virtual page is not on the swap device. It decrements the swap-

use count for the page and if count drops to 0, frees the swap space.

For which kind of fault the page is checked first?

The page is first checked for the validity fault, as soon as it is found that the page is

invalid (valid bit is clear), the validity fault handler returns immediately, and the

process incur the validity page fault. Kernel handles the validity fault and the process

will incur the protection fault if any one is present.

In what way the protection fault handler concludes?

After finishing the execution of the fault handler, it sets the modify and protection bits

and clears the copy on write bit. It recalculates the process-priority and checks for

signals.

How the Kernel handles both the page stealer and the fault handler? The page stealer and the fault handler thrash because of the shortage of the memory. If

the sum of the working sets of all processes is greater that the physical memory then

the fault handler will usually sleep because it cannot allocate pages for a process. This

results in the reduction of the system throughput because Kernel spends too much time

in overhead, rearranging the memory in the frantic pace.

Explain different types of Unix systems. The most widely used are: 1. System V (AT&T) 2. AIX (IBM) 3. BSD (Berkeley) 4.

Solaris (Sun) 5. Xenix ( A PC version of Unix)

Explain kernal and shell.

Kernal: It carries out basic operating system functions such as allocating memory,

accessing files and handling communications. Shell:A shell provides the user interface

to the kernal.There are 3 major shells : C-shell, Bourne shell , Korn shell

© Copyright : IT Engg Portal – www.itportal.in 308

What is ex and vi ? ex is Unix line editor and vi is the standard Unix screen editor.

Which are typical system directories below the root directory? (1)/bin: contains many programs which will be executed by users (2)/etc : files used by

administrator (3)/dev: hardware devices (4)/lib: system libraries (5)/usr: application

software (6)/home: home directories for different systems.

Construct pipes to execute the following jobs.

1. Output of who should be displayed on the screen with value of total number of users

who have logged in displayed at the bottom of the list.

2. Output of ls should be displayed on the screen and from this output the lines

containing the word ‗poem‘ should be counted and the count should be stored in a file.

3. Contents of file1 and file2 should be displayed on the screen and this output should

be appended in a file

.

From output of ls the lines containing ‗poem‘ should be displayed on the screen along

with the count.

4. Name of cities should be accepted from the keyboard . This list should be combined

with the list present in a file. This combined list should be sorted and the sorted list

should be stored in a file ‗newcity‘.

5. All files present in a directory dir1 should be deleted any error while deleting should

be stored in a file ‗errorlog‘.

Explain the following commands. $ ls > file1

$ banner hi-fi > message

$ cat par.3 par.4 par.5 >> report

$ cat file1>file1

$ date ; who

$ date ; who > logfile

$ (date ; who) > logfile

What is the significance of the “tee” command? It reads the standard input and sends it to the standard output while redirecting a copy

of what it has read to the file specified by the user.

© Copyright : IT Engg Portal – www.itportal.in 309

What does the command “ $who | sort –logfile > newfile” do? The input from a pipe can be combined with the input from a file . The trick is to use

the special symbol ―-― (a hyphen) for those commands that recognize the hyphen as

std input.

In the above command the output from who becomes the std input to sort , meanwhile

sort opens the file logfile, the contents of this file is sorted together with the output of

who (rep by the hyphen) and the sorted output is redirected to the file newfile.

What does the command “$ls | wc –l > file1” do?

ls becomes the input to wc which counts the number of lines it receives as input and

instead of displaying this count , the value is stored in file1.

Which of the following commands is not a filter man , (b) cat , (c) pg , (d) head man A filter is a program which can receive a flow of data from std input, process (or

filter) it and send the result to the std output.

How is the command “$cat file2 “ different from “$cat >file2 and >> redirection

operators ? is the output redirection operator when used it overwrites while >> operator appends

into the file.

Explain the steps that a shell follows while processing a command. After the command line is terminated by the key, the shell goes ahead with processing

the command line in one or more passes. The sequence is well defined and assumes

the following order.

Parsing: The shell first breaks up the command line into words, using spaces and the

delimiters, unless quoted. All consecutive occurrences of a space or tab are replaced

here with a single space.

Variable evaluation: All words preceded by a $ are valuated as variables, unless

quoted or escaped.

Command substitution: Any command surrounded by back quotes is executed by the

shell which then replaces the standard output of the command into the command line.

Wild-card interpretation: The shell finally scans the command line for wild-cards (the

characters *, ?, [, ]).

Any word containing a wild-card is replaced by a sorted list of

filenames that match the pattern. The list of these filenames then forms the arguments

to the command.

© Copyright : IT Engg Portal – www.itportal.in 310

PATH evaluation: It finally looks for the PATH variable to determine the sequence of

directories it has to search in order to hunt for the command.

What difference between cmp and diff commands? cmp - Compares two files byte by byte and displays the first mismatch diff - tells the

changes to be made to make the files identical

What is the use of „grep‟ command?

‗grep‘ is a pattern search command. It searches for the pattern, specified in the

command line with appropriate option, in a file(s).

Syntax : grep

Example : grep 99mx mcafile

What is the difference between cat and more command? Cat displays file contents. If the file is large the contents scroll off the screen before

we view it. So command 'more' is like a pager which displays the contents page by

page.

Write a command to kill the last background job? Kill $!

Which command is used to delete all files in the current directory and all its sub-

directories? rm -r *

Write a command to display a file‟s contents in various formats? $od -cbd file_name

c - character, b - binary (octal), d-decimal, od=Octal Dump.

What will the following command do? $ echo *

It is similar to 'ls' command and displays all the files in the current directory.

Is it possible to create new a file system in UNIX? Yes, ‗mkfs‘ is used to create a new file system.

Is it possible to restrict incoming message?

Yes, using the ‗mesg‘ command.

© Copyright : IT Engg Portal – www.itportal.in 311

What is the use of the command "ls -x chapter[1-5]" ls stands for list; so it displays the list of the files that starts with 'chapter' with suffix

'1' to '5', chapter1, chapter2, and so on.

Is „du‟ a command? If so, what is its use? Yes, it stands for ‗disk usage‘. With the help of this command you can find the disk

capacity and free space of the disk.

Is it possible to count number char, line in a file; if so, How? Yes, wc-stands for word count.

wc -c for counting number of characters in a file.

wc -l for counting lines in a file.

Name the data structure used to maintain file identification? ‗inode‘, each file has a separate inode and a unique inode number.

How many prompts are available in a UNIX system?

Two prompts, PS1 (Primary Prompt), PS2 (Secondary Prompt).

How does the kernel differentiate device files and ordinary files? Kernel checks 'type' field in the file's inode structure.

How to switch to a super user status to gain privileges? Use ‗su‘ command. The system asks for password and when valid entry is made the

user gains super user (admin) privileges.

What are shell variables? Shell variables are special variables, a name-value pair created and maintained by the

shell.

Example: PATH, HOME, MAIL and TERM

What is redirection? Directing the flow of data to the file or from the file for input or output.

Example : ls > wc

How to terminate a process which is running and the specialty on command kill

0? With the help of kill command we can terminate the process.

© Copyright : IT Engg Portal – www.itportal.in 312

Syntax: kill pid

Kill 0 - kills all processes in your system except the login shell.

What is a pipe and give an example? A pipe is two or more commands separated by pipe char '|'. That tells the shell to

arrange for the output of the preceding command to be passed as input to the following

command.

Example : ls -l | pr

The output for a command ls is the standard input of pr.

When a sequence of commands are combined using pipe, then it is called pipeline.

Explain kill() and its possible return values. There are four possible results from this call:

‗kill()‘ returns 0. This implies that a process exists with the given PID, and the system

would allow you to send signals to it. It is system-dependent whether the process

could be a zombie.

‗kill()‘ returns -1, ‗errno == ESRCH‘ either no process exists with the given PID, or

security enhancements are causing the system to deny its existence. (On some systems,

the process could be a zombie.)

‗kill()‘ returns -1, ‗errno == EPERM‘ the system would not allow you to kill the

specified process. This means that either the process exists (again, it could be a

zombie) or draconian security enhancements are present (e.g. your process is not

allowed to send signals to *anybody*).

‗kill()‘ returns -1, with some other value of ‗errno‘ you are in trouble! The most-used

technique is to assume that success or failure with ‗EPERM‘ implies that the process

exists, and any other error implies that it doesn't.

An alternative exists, if you are writing specifically for a system (or all those systems)

that provide a ‗/proc‘ filesystem: checking for the existence of ‗/proc/PID‘ may work.

=====================================================================

© Copyright : IT Engg Portal – www.itportal.in 313

Software Testing

Interview Questions &

Answers

© Copyright : IT Engg Portal – www.itportal.in 314

Manual Testing Interview Questions and Answers

What makes a good test engineer?

A good test engineer has a 'test to break' attitude, an ability to take the point of view of

the customer, a strong desire for quality, and an attention to detail. Tact and diplomacy

are useful in maintaining a cooperative relationship with developers, and an ability to

communicate with both technical (developers) and non-technical (customers,

management) people is useful. Previous software development experience can be

helpful as it provides a deeper understanding of the software development process,

gives the tester an appreciation for the developers' point of view, and reduce the

learning curve in automated test tool programming. Judgment skills are needed to

assess high-risk areas of an application on which to focus testing efforts when time is

limited.

What makes a good Software QA engineer? The same qualities a good tester has are useful for a QA engineer. Additionally, they

must be able to understand the entire software development process and how it can fit

into the business approach and goals of the organization. Communication skills and

the ability to understand various sides of issues are important. In organizations in the

early stages of implementing QA processes, patience and diplomacy are especially

needed. An ability to find problems as well as to see 'what's missing' is important for

inspections and reviews.

What makes a good QA or Test manager?

A good QA, test, or QA/Test(combined) manager should:

• be familiar with the software development process

• be able to maintain enthusiasm of their team and promote a positive atmosphere,

despite

• what is a somewhat 'negative' process (e.g., looking for or preventing problems)

• be able to promote teamwork to increase productivity

• be able to promote cooperation between software, test, and QA engineers

• have the diplomatic skills needed to promote improvements in QA processes

• have the ability to withstand pressures and say 'no' to other managers when quality is

insufficient or QA processes are not being adhered to

• have people judgement skills for hiring and keeping skilled personnel

• be able to communicate with technical and non-technical people, engineers,

© Copyright : IT Engg Portal – www.itportal.in 315

managers, and customers.

• be able to run meetings and keep them focused

What's the role of documentation in QA? Critical. (Note that documentation can be electronic, not necessarily paper.) QA

practices should be documented such that they are repeatable. Specifications, designs,

business rules, inspection reports, configurations, code changes, test plans, test cases,

bug reports, user manuals, etc. should all be documented. There should ideally be a

system for easily finding and obtaining documents and determining what

documentation will have a particular piece of information. Change management for

documentation should be used if possible.

What's the big deal about 'requirements'?

One of the most reliable methods of insuring problems, or failure, in a complex

software project is to have poorly documented requirements specifications.

Requirements are the details describing an application's externally-perceived

functionality and properties. Requirements should be clear, complete, reasonably

detailed, cohesive, attainable, and testable. A non-testable requirement would be, for

example, 'user-friendly' (too subjective). A testable requirement would be something

like 'the user must enter their previously-assigned password to access the application'.

Determining and organizing requirements details in a useful and efficient way can be a

difficult effort; different methods are available depending on the particular project.

Many books are available that describe various approaches to this task. (See the

Bookstore section's 'Software Requirements Engineering' category for books on

Software Requirements.)

Care should be taken to involve ALL of a project's significant 'customers' in the

requirements process. 'Customers' could be in-house personnel or out, and could

include end-users, customer acceptance testers, customer contract officers, customer

management, future software maintenance engineers, salespeople, etc. Anyone who

could later derail the project if their expectations aren't met should be included if

possible.

Organizations vary considerably in their handling of requirements specifications.

Ideally, the requirements are spelled out in a document with statements such as 'The

product shall.....'. 'Design' specifications should not be confused with 'requirements';

design specifications should be traceable back to the requirements.

In some organizations requirements may end up in high level project plans, functional

© Copyright : IT Engg Portal – www.itportal.in 316

specification documents, in design documents, or in other documents at various levels

of detail. No matter what they are called, some type of documentation with detailed

requirements will be needed by testers in order to properly plan and execute tests.

Without such documentation, there will be no clear-cut way to determine if a software

application is performing correctly.

'Agile' methods such as XP use methods requiring close interaction and cooperation

between programmers and customers/end-users to iteratively develop requirements.

The programmer uses 'Test first' development to first create automated unit testing

code, which essentially embodies the requirements.

What steps are needed to develop and run software tests? The following are some of the steps to consider:

• Obtain requirements, functional design, and internal design specifications and other

necessary documents

• Obtain budget and schedule requirements

• Determine project-related personnel and their responsibilities, reporting

requirements, required standards and processes (such as release processes, change

processes, etc.)

• Identify application's higher-risk aspects, set priorities, and determine scope and

limitations of tests

• Determine test approaches and methods - unit, integration, functional, system, load,

usability tests, etc.

• Determine test environment requirements (hardware, software, communications,

etc.)

• Determine testware requirements (record/playback tools, coverage analyzers, test

tracking, problem/bug tracking, etc.)

• Determine test input data requirements

• Identify tasks, those responsible for tasks, and labor requirements

• Set schedule estimates, timelines, milestones

• Determine input equivalence classes, boundary value analyses, error classes

• Prepare test plan document and have needed reviews/approvals

• Write test cases

• Have needed reviews/inspections/approvals of test cases

• Prepare test environment and testware, obtain needed user manuals/reference

documents/configuration guides/installation guides, set up test tracking processes, set

up logging and archiving processes, set up or obtain test input data

• Obtain and install software releases

© Copyright : IT Engg Portal – www.itportal.in 317

• Perform tests

• Evaluate and report results

• Track problems/bugs and fixes

• Retest as needed

• Maintain and update test plans, test cases, test environment, and testware through life

cycle

What's a 'test plan'?

A software project test plan is a document that describes the objectives, scope,

approach, and focus of a software testing effort. The process of preparing a test plan is

a useful way to think through the efforts needed to validate the acceptability of a

software product. The completed document will help people outside the test group

understand the 'why' and 'how' of product validation. It should be thorough enough to

be useful but not so thorough that no one outside the test group will read it. The

following are some of the items that might be included in a test plan, depending on the

particular project:

• Title

• Identification of software including version/release numbers

• Revision history of document including authors, dates, approvals

• Table of Contents

• Purpose of document, intended audience

• Objective of testing effort

• Software product overview

• Relevant related document list, such as requirements, design documents, other test

plans, etc.

• Relevant standards or legal requirements

• Traceability requirements

• Relevant naming conventions and identifier conventions

• Overall software project organization and personnel/contact-info/responsibilties

• Test organization and personnel/contact-info/responsibilities

• Assumptions and dependencies

• Project risk analysis

• Testing priorities and focus

• Scope and limitations of testing

• Test outline - a decomposition of the test approach by test type, feature,

functionality, process, system, module, etc. as applicable

• Outline of data input equivalence classes, boundary value analysis, error classes

© Copyright : IT Engg Portal – www.itportal.in 318

• Test environment - hardware, operating systems, other required software, data

configurations, interfaces to other systems

• Test environment validity analysis - differences between the test and production

systems and their impact on test validity.

• Test environment setup and configuration issues

• Software migration processes

• Software CM processes

• Test data setup requirements

• Database setup requirements

• Outline of system-logging/error-logging/other capabilities, and tools such as screen

capture software, that will be used to help describe and report bugs

• Discussion of any specialized software or hardware tools that will be used by testers

to help track the cause or source of bugs

• Test automation - justification and overview

• Test tools to be used, including versions, patches, etc.

• Test script/test code maintenance processes and version control

• Problem tracking and resolution - tools and processes

• Project test metrics to be used

• Reporting requirements and testing deliverables

• Software entrance and exit criteria

• Initial sanity testing period and criteria

• Test suspension and restart criteria

• Personnel allocation

• Personnel pre-training needs

• Test site/location

• Outside test organizations to be utilized and their purpose, responsibilties,

deliverables, contact persons, and coordination issues

• Relevant proprietary, classified, security, and licensing issues.

• Open issues

• Appendix - glossary, acronyms, etc.

What's a 'test case'?

• A test case is a document that describes an input, action, or event and an expected

response, to determine if a feature of an application is working correctly. A test case

should contain particulars such as test case identifier, test case name, objective, test

conditions/setup, input data requirements, steps, and expected results.

© Copyright : IT Engg Portal – www.itportal.in 319

• Note that the process of developing test cases can help find problems in the

requirements or design of an application, since it requires completely thinking through

the operation of the application. For this reason, it's useful to prepare test cases early in

the development cycle if possible.

What should be done after a bug is found? The bug needs to be communicated and assigned to developers that can fix it. After the

problem is resolved, fixes should be re-tested, and determinations made regarding

requirements for regression testing to check that fixes didn't create problems

elsewhere. If a problem-tracking system is in place, it should encapsulate these

processes. A variety of commercial problem-tracking/management software tools are

available (see the 'Tools' section for web resources with listings of such tools). The

following are items to consider in the tracking process:

• Complete information such that developers can understand the bug, get an idea of it's

severity, and reproduce it if necessary.

• Bug identifier (number, ID, etc.)

• Current bug status (e.g., 'Released for Retest', 'New', etc.)

• The application name or identifier and version

• The function, module, feature, object, screen, etc. where the bug occurred

• Environment specifics, system, platform, relevant hardware specifics

• Test case name/number/identifier

• One-line bug description

• Full bug description

• Description of steps needed to reproduce the bug if not covered by a test case or if

the developer doesn't have easy access to the test case/test script/test tool

• Names and/or descriptions of file/data/messages/etc. used in test

• File excerpts/error messages/log file excerpts/screen shots/test tool logs that would

be helpful in finding the cause of the problem

• Severity estimate (a 5-level range such as 1-5 or 'critical'-to-'low' is common)

• Was the bug reproducible?

• Tester name

• Test date

• Bug reporting date

• Name of developer/group/organization the problem is assigned to

• Description of problem cause

• Description of fix

• Code section/file/module/class/method that was fixed

© Copyright : IT Engg Portal – www.itportal.in 320

• Date of fix

• Application version that contains the fix

• Tester responsible for retest

• Retest date

• Retest results

• Regression testing requirements

• Tester responsible for regression tests

• Regression testing results

A reporting or tracking process should enable notification of appropriate personnel at

various stages. For instance, testers need to know when retesting is needed, developers

need to know when bugs are found and how to get the needed information, and

reporting/summary capabilities are needed for managers.

What is 'configuration management'?

Configuration management covers the processes used to control, coordinate, and track:

code, requirements, documentation, problems, change requests, designs,

tools/compilers/libraries/patches, changes made to them, and who makes the changes.

(See the 'Tools' section for web resources with listings of configuration management

tools. Also see the Bookstore section's 'Configuration Management' category for useful

books with more information.)

What if the software is so buggy it can't really be tested at all? The best bet in this situation is for the testers to go through the process of reporting

whatever bugs or blocking-type problems initially show up, with the focus being on

critical bugs. Since this type of problem can severely affect schedules, and indicates

deeper problems in the software development process (such as insufficient unit testing

or insufficient integration testing, poor design, improper build or release procedures,

etc.) managers should be notified, and provided with some documentation as evidence

of the problem.

How can it be known when to stop testing? This can be difficult to determine. Many modern software applications are so complex,

and run in such an interdependent environment, that complete testing can never be

done. Common factors in deciding when to stop are:

• Deadlines (release deadlines, testing deadlines, etc.)

• Test cases completed with certain percentage passed

• Test budget depleted

© Copyright : IT Engg Portal – www.itportal.in 321

• Coverage of code/functionality/requirements reaches a specified point

• Bug rate falls below a certain level

• Beta or alpha testing period ends

What if there isn't enough time for thorough testing? Use risk analysis to determine where testing should be focused.

Since it's rarely possible to test every possible aspect of an application, every possible

combination of events, every dependency, or everything that could go wrong, risk

analysis is appropriate to most software development projects. This requires

judgement skills, common sense, and experience. (If warranted, formal methods are

also available.) Considerations can include:

• Which functionality is most important to the project's intended purpose?

• Which functionality is most visible to the user?

• Which functionality has the largest safety impact?

• Which functionality has the largest financial impact on users?

• Which aspects of the application are most important to the customer?

• Which aspects of the application can be tested early in the development cycle?

• Which parts of the code are most complex, and thus most subject to errors?

• Which parts of the application were developed in rush or panic mode?

• Which aspects of similar/related previous projects caused problems?

• Which aspects of similar/related previous projects had large maintenance expenses?

• Which parts of the requirements and design are unclear or poorly thought out?

• What do the developers think are the highest-risk aspects of the application?

• What kinds of problems would cause the worst publicity?

• What kinds of problems would cause the most customer service complaints?

• What kinds of tests could easily cover multiple functionalities?

• Which tests will have the best high-risk-coverage to time-required ratio?

What if the project isn't big enough to justify extensive testing? Consider the impact of project errors, not the size of the project. However, if extensive

testing is still not justified, risk analysis is again needed and the same considerations

as described previously in 'What if there isn't enough time for thorough testing?' apply.

The tester might then do ad hoc testing, or write up a limited test plan based on the

risk analysis.

What can be done if requirements are changing continuously? A common problem and a major headache.

© Copyright : IT Engg Portal – www.itportal.in 322

• Work with the project's stakeholders early on to understand how requirements might

change so that alternate test plans and strategies can be worked out in advance, if

possible.

• It's helpful if the application's initial design allows for some adaptability so that later

changes do not require redoing the application from scratch.

• If the code is well-commented and well-documented this makes changes easier for

the developers.

• Use rapid prototyping whenever possible to help customers feel sure of their

requirements and minimize changes.

• The project's initial schedule should allow for some extra time commensurate with

the possibility of changes.

• Try to move new requirements to a 'Phase 2' version of an application, while using

the original requirements for the 'Phase 1' version.

• Negotiate to allow only easily-implemented new requirements into the project, while

moving more difficult new requirements into future versions of the application.

• Be sure that customers and management understand the scheduling impacts, inherent

risks, and costs of significant requirements changes. Then let management or the

customers (not the developers or testers) decide if the changes are warranted - after all,

that's their job.

• Balance the effort put into setting up automated testing with the expected effort

required to re-do them to deal with changes.

• Try to design some flexibility into automated test scripts.

• Focus initial automated testing on application aspects that are most likely to remain

unchanged.

• Devote appropriate effort to risk analysis of changes to minimize regression testing

needs.

• Design some flexibility into test cases (this is not easily done; the best bet might be

to minimize the detail in the test cases, or set up only higher-level generic-type test

plans)

• Focus less on detailed test plans and test cases and more on ad hoc testing (with an

understanding of the added risk that this entails).

What if the application has functionality that wasn't in the requirements?

It may take serious effort to determine if an application has significant unexpected or

hidden functionality, and it would indicate deeper problems in the software

development process. If the functionality isn't necessary to the purpose of the

application, it should be removed, as it may have unknown impacts or dependencies

© Copyright : IT Engg Portal – www.itportal.in 323

that were not taken into account by the designer or the customer. If not removed,

design information will be needed to determine added testing needs or regression

testing needs. Management should be made aware of any significant added risks as a

result of the unexpected functionality. If the functionality only effects areas such as

minor improvements in the user interface, for example, it may not be a significant risk.

How can Software QA processes be implemented without stifling productivity? By implementing QA processes slowly over time, using consensus to reach agreement

on processes, and adjusting and experimenting as an organization grows and matures,

productivity will be improved instead of stifled. Problem prevention will lessen the

need for problem detection, panics and burn-out will decrease, and there will be

improved focus and less wasted effort. At the same time, attempts should be made to

keep processes simple and efficient, minimize paperwork, promote computer-based

processes and automated tracking and reporting, minimize time required in meetings,

and promote training as part of the QA process. However, no one - especially talented

technical types - likes rules or bureacracy, and in the short run things may slow down

a bit. A typical scenario would be that more days of planning and development will be

needed, but less time will be required for late-night bug-fixing and calming of irate

customers.

What if an organization is growing so fast that fixed QA processes are

impossible? This is a common problem in the software industry, especially in new technology

areas. There is no easy solution in this situation, other than:

• Hire good people

• Management should 'ruthlessly prioritize' quality issues and maintain focus on the

customer

• Everyone in the organization should be clear on what 'quality' means to the customer

How does a client/server environment affect testing? Client/server applications can be quite complex due to the multiple dependencies

among clients, data communications, hardware, and servers. Thus testing requirements

can be extensive. When time is limited (as it usually is) the focus should be on

integration and system testing. Additionally, load/stress/performance testing may be

useful in determining client/server application limitations and capabilities. There are

commercial tools to assist with such testing. (See the 'Tools' section for web resources

with listings that include these kinds of test tools.)

© Copyright : IT Engg Portal – www.itportal.in 324

How can World Wide Web sites be tested? Web sites are essentially client/server applications - with web servers and 'browser'

clients. Consideration should be given to the interactions between html pages, TCP/IP

communications, Internet connections, firewalls, applications that run in web pages

(such as applets, javascript, plug-in applications), and applications that run on the

server side (such as cgi scripts, database interfaces, logging applications, dynamic

page generators, asp, etc.). Additionally, there are a wide variety of servers and

browsers, various versions of each, small but sometimes significant differences

between them, variations in connection speeds, rapidly changing technologies, and

multiple standards and protocols. The end result is that testing for web sites can

become a major ongoing effort. Other considerations might include:

• What are the expected loads on the server (e.g., number of hits per unit time?), and

what kind of performance is required under such loads (such as web server response

time, database query response times). What kinds of tools will be needed for

performance testing (such as web load testing tools, other tools already in house that

can be adapted, web robot downloading tools, etc.)?

• Who is the target audience? What kind of browsers will they be using? What kind of

connection speeds will they by using? Are they intra- organization (thus with likely

high connection speeds and similar browsers) or Internet-wide (thus with a wide

variety of connection speeds and browser types)?

• What kind of performance is expected on the client side (e.g., how fast should pages

appear, how fast should animations, applets, etc. load and run)?

• Will down time for server and content maintenance/upgrades be allowed? how

much?

• What kinds of security (firewalls, encryptions, passwords, etc.) will be required and

what is it expected to do? How can it be tested?

• How reliable are the site's Internet connections required to be? And how does that

affect backup system or redundant connection requirements and testing?

• What processes will be required to manage updates to the web site's content, and

what are the requirements for maintaining, tracking, and controlling page content,

graphics, links, etc.?

• Which HTML specification will be adhered to? How strictly? What variations will

be allowed for targeted browsers?

• Will there be any standards or requirements for page appearance and/or graphics

throughout a site or parts of a site??

• How will internal and external links be validated and updated? how often?

• Can testing be done on the production system, or will a separate test system be

© Copyright : IT Engg Portal – www.itportal.in 325

required? How are browser caching, variations in browser option settings, dial-up

connection variabilities, and real-world internet 'traffic congestion' problems to be

accounted for in testing?

• How extensive or customized are the server logging and reporting requirements; are

they considered an integral part of the system and do they require testing?

• How are cgi programs, applets, javascripts, ActiveX components, etc. to be

maintained, tracked, controlled, and tested?

Some sources of site security information include the Usenet newsgroup

'comp.security.announce' and links concerning web site security in the 'Other

Resources' section.

Some usability guidelines to consider - these are subjective and may or may not apply

to a given situation (Note: more information on usability testing issues can be found in

articles about web site usability in the 'Other Resources' section):

• Pages should be 3-5 screens max unless content is tightly focused on a single topic.

If larger, provide internal links within the page.

• The page layouts and design elements should be consistent throughout a site, so that

it's clear to the user that they're still within a site.

• Pages should be as browser-independent as possible, or pages should be provided or

generated based on the browser-type.

• All pages should have links external to the page; there should be no dead-end pages.

• The page owner, revision date, and a link to a contact person or organization should

be included on each page.

Many new web site test tools have appeared in the recent years and more than 280 of

them are listed in the 'Web Test Tools' section.

How is testing affected by object-oriented designs?

Well-engineered object-oriented design can make it easier to trace from code to

internal design to functional design to requirements. While there will be little affect on

black box testing (where an understanding of the internal design of the application is

unnecessary), white-box testing can be oriented to the application's objects. If the

application was well-designed this can simplify test design.

What is Extreme Programming and what's it got to do with testing? Extreme Programming (XP) is a software development approach for small teams on

risk-prone projects with unstable requirements. It was created by Kent Beck who

described the approach in his book 'Extreme Programming Explained' (See the

Softwareqatest.com Books page.). Testing ('extreme testing') is a core aspect of

© Copyright : IT Engg Portal – www.itportal.in 326

Extreme Programming. Programmers are expected to write unit and functional test

code first - before the application is developed. Test code is under source control along

with the rest of the code. Customers are expected to be an integral part of the project

team and to help develope scenarios for acceptance/black box testing. Acceptance tests

are preferably automated, and are modified and rerun for each of the frequent

development iterations. QA and test personnel are also required to be an integral part

of the project team. Detailed requirements documentation is not used, and frequent re-

scheduling, re-estimating, and re-prioritizing is expected. For more info see the XP-

related listings in the Softwareqatest.com 'Other Resources' section.

What is 'Software Quality Assurance'? Software QA involves the entire software development PROCESS - monitoring and

improving the process, making sure that any agreed-upon standards and procedures are

followed, and ensuring that problems are found and dealt with. It is oriented to

'prevention'. (See the Bookstore section's 'Software QA' category for a list of useful

books on Software Quality Assurance.)

What is 'Software Testing'? Testing involves operation of a system or application under controlled conditions and

evaluating the results (eg, 'if the user is in interface A of the application while using

hardware B, and does C, then D should happen'). The controlled conditions should

include both normal and abnormal conditions. Testing should intentionally attempt to

make things go wrong to determine if things happen when they shouldn't or things

don't happen when they should. It is oriented to 'detection'. (See the Bookstore

section's 'Software Testing' category for a list of useful books on Software Testing.)

• Organizations vary considerably in how they assign responsibility for QA and

testing. Sometimes they're the combined responsibility of one group or individual.

Also common are project teams that include a mix of testers and developers who work

closely together, with overall QA processes monitored by project managers. It will

depend on what best fits an organization's size and business structure.

What are some recent major computer system failures caused by software bugs? • A major U.S. retailer was reportedly hit with a large government fine in October of

2003 due to web site errors that enabled customers to view one anothers' online

orders.

• News stories in the fall of 2003 stated that a manufacturing company recalled all

their transportation products in order to fix a software problem causing instability in

© Copyright : IT Engg Portal – www.itportal.in 327

certain circumstances. The company found and reported the bug itself and initiated the

recall procedure in which a software upgrade fixed the problems.

• In August of 2003 a U.S. court ruled that a lawsuit against a large online brokerage

company could proceed; the lawsuit reportedly involved claims that the company was

not fixing system problems that sometimes resulted in failed stock trades, based on the

experiences of 4 plaintiffs during an 8-month period. A previous lower court's ruling

that "...six miscues out of more than 400 trades does not indicate negligence." was

invalidated.

• In April of 2003 it was announced that the largest student loan company in the U.S.

made a software error in calculating the monthly payments on 800,000 loans.

Although borrowers were to be notified of an increase in their required payments, the

company will still reportedly lose $8 million in interest. The error was uncovered

when borrowers began reporting inconsistencies in their bills.

• News reports in February of 2003 revealed that the U.S. Treasury Department mailed

50,000 Social Security checks without any beneficiary names. A spokesperson

indicated that the missing names were due to an error in a software change.

Replacement checks were subsequently mailed out with the problem corrected, and

recipients were then able to cash their Social Security checks.

• In March of 2002 it was reported that software bugs in Britain's national tax system

resulted in more than 100,000 erroneous tax overcharges. The problem was partly

attibuted to the difficulty of testing the integration of multiple systems.

• A newspaper columnist reported in July 2001 that a serious flaw was found in off-

the-shelf software that had long been used in systems for tracking certain U.S. nuclear

materials. The same software had been recently donated to another country to be used

in tracking their own nuclear materials, and it was not until scientists in that country

discovered the problem, and shared the information, that U.S. officials became aware

of the problems.

• According to newspaper stories in mid-2001, a major systems development

contractor was fired and sued over problems with a large retirement plan management

system. According to the reports, the client claimed that system deliveries were late,

the software had excessive defects, and it caused other systems to crash.

• In January of 2001 newspapers reported that a major European railroad was hit by

the aftereffects of the Y2K bug. The company found that many of their newer trains

would not run due to their inability to recognize the date '31/12/2000'; the trains were

started by altering the control system's date settings.

• News reports in September of 2000 told of a software vendor settling a lawsuit with

a large mortgage lender; the vendor had reportedly delivered an online mortgage

© Copyright : IT Engg Portal – www.itportal.in 328

processing system that did not meet specifications, was delivered late, and didn't

work.

• In early 2000, major problems were reported with a new computer system in a large

suburban U.S. public school district with 100,000+ students; problems included

10,000 erroneous report cards and students left stranded by failed class registration

systems; the district's CIO was fired. The school district decided to reinstate it's

original 25-year old system for at least a year until the bugs were worked out of the

new system by the software vendors.

• In October of 1999 the $125 million NASA Mars Climate Orbiter spacecraft was

believed to be lost in space due to a simple data conversion error. It was determined

that spacecraft software used certain data in English units that should have been in

metric units. Among other tasks, the orbiter was to serve as a communications relay

for the Mars Polar Lander mission, which failed for unknown reasons in December

1999. Several investigating panels were convened to determine the process failures

that allowed the error to go undetected.

• Bugs in software supporting a large commercial high-speed data network affected

70,000 business customers over a period of 8 days in August of 1999. Among those

affected was the electronic trading system of the largest U.S. futures exchange, which

was shut down for most of a week as a result of the outages.

• In April of 1999 a software bug caused the failure of a $1.2 billion U.S. military

satellite launch, the costliest unmanned accident in the history of Cape Canaveral

launches. The failure was the latest in a string of launch failures, triggering a complete

military and industry review of U.S. space launch programs, including software

integration and testing processes. Congressional oversight hearings were requested.

• A small town in Illinois in the U.S. received an unusually large monthly electric bill

of $7 million in March of 1999. This was about 700 times larger than its normal bill. It

turned out to be due to bugs in new software that had been purchased by the local

power company to deal with Y2K software issues.

• In early 1999 a major computer game company recalled all copies of a popular new

product due to software problems. The company made a public apology for releasing a

product before it was ready.

Why is it often hard for management to get serious about quality assurance?

Solving problems is a high-visibility process; preventing problems is low-visibility.

This is illustrated by an old parable:

In ancient China there was a family of healers, one of whom was known throughout

the land and employed as a physician to a great lord. The physician was asked which

© Copyright : IT Engg Portal – www.itportal.in 329

of his family was the most skillful healer. He replied,

"I tend to the sick and dying with drastic and dramatic treatments, and on occasion

someone is cured and my name gets out among the lords."

"My elder brother cures sickness when it just begins to take root, and his skills are

known among the local peasants and neighbors."

"My eldest brother is able to sense the spirit of sickness and eradicate it before it takes

form. His name is unknown outside our home."

Why does software have bugs? • miscommunication or no communication - as to specifics of what an application

should or shouldn't do (the application's requirements).

• software complexity - the complexity of current software applications can be difficult

to comprehend for anyone without experience in modern-day software development.

Windows-type interfaces, client-server and distributed applications, data

communications, enormous relational databases, and sheer size of applications have all

contributed to the exponential growth in software/system complexity. And the use of

object-oriented techniques can complicate instead of simplify a project unless it is

well-engineered.

• programming errors - programmers, like anyone else, can make mistakes.

• changing requirements (whether documented or undocumented) - the customer may

not understand the effects of changes, or may understand and request them anyway -

redesign, rescheduling of engineers, effects on other projects, work already completed

that may have to be redone or thrown out, hardware requirements that may be affected,

etc. If there are many minor changes or any major changes, known and unknown

dependencies among parts of the project are likely to interact and cause problems, and

the complexity of coordinating changes may result in errors. Enthusiasm of

engineering staff may be affected. In some fast-changing business environments,

continuously modified requirements may be a fact of life. In this case, management

must understand the resulting risks, and QA and test engineers must adapt and plan for

continuous extensive testing to keep the inevitable bugs from running out of control -

see 'What can be done if requirements are changing continuously?' in Part 2 of the

FAQ.

• time pressures - scheduling of software projects is difficult at best, often requiring a

lot of guesswork. When deadlines loom and the crunch comes, mistakes will be made.

• egos - people prefer to say things like:

'no problem'

'piece of cake'

© Copyright : IT Engg Portal – www.itportal.in 330

'I can whip that out in a few hours'

'it should be easy to update that old code'

instead of:

'that adds a lot of complexity and we could end up

making a lot of mistakes'

'we have no idea if we can do that; we'll wing it'

'I can't estimate how long it will take, until I

take a close look at it'

'we can't figure out what that old spaghetti code

did in the first place'

If there are too many unrealistic 'no problem's', the result is bugs.

• poorly documented code - it's tough to maintain and modify code that is badly

written or poorly documented; the result is bugs. In many organizations management

provides no incentive for programmers to document their code or write clear,

understandable, maintainable code. In fact, it's usually the opposite: they get points

mostly for quickly turning out code, and there's job security if nobody else can

understand it ('if it was hard to write, it should be hard to read').

• software development tools - visual tools, class libraries, compilers, scripting tools,

etc. often introduce their own bugs or are poorly documented, resulting in added bugs.

How can new Software QA processes be introduced in an existing organization? • A lot depends on the size of the organization and the risks involved. For large

organizations with high-risk (in terms of lives or property) projects, serious

management buy-in is required and a formalized QA process is necessary.

• Where the risk is lower, management and organizational buy-in and QA

implementation may be a slower, step-at-a-time process. QA processes should be

balanced with productivity so as to keep bureaucracy from getting out of hand.

• For small groups or projects, a more ad-hoc process may be appropriate, depending

on the type of customers and projects. A lot will depend on team leads or managers,

feedback to developers, and ensuring adequate communications among customers,

managers, developers, and testers.

• The most value for effort will be in (a) requirements management processes, with a

goal of clear, complete, testable requirement specifications embodied in requirements

or design documentation and (b) design inspections and code inspections.

© Copyright : IT Engg Portal – www.itportal.in 331

What is verification? validation? Verification typically involves reviews and meetings to evaluate documents, plans,

code, requirements, and specifications. This can be done with checklists, issues lists,

walkthroughs, and inspection meetings. Validation typically involves actual testing

and takes place after verifications are completed. The term 'IV & V' refers to

Independent Verification and Validation.

What is a 'walkthrough'? A 'walkthrough' is an informal meeting for evaluation or informational purposes. Little

or no preparation is usually required.

What's an 'inspection'? An inspection is more formalized than a 'walkthrough', typically with 3-8 people

including a moderator, reader, and a recorder to take notes. The subject of the

inspection is typically a document such as a requirements spec or a test plan, and the

purpose is to find problems and see what's missing, not to fix anything. Attendees

should prepare for this type of meeting by reading thru the document; most problems

will be found during this preparation. The result of the inspection meeting should be a

written report. Thorough preparation for inspections is difficult, painstaking work, but

is one of the most cost effective methods of ensuring quality. Employees who are most

skilled at inspections are like the 'eldest brother' in the parable in 'Why is it often hard

for management to get serious about quality assurance?'. Their skill may have low

visibility but they are extremely valuable to any software development organization,

since bug prevention is far more cost-effective than bug detection.

What kinds of testing should be considered?

• Black box testing - not based on any knowledge of internal design or code. Tests are

based on requirements and functionality.

• White box testing - based on knowledge of the internal logic of an application's code.

Tests are based on coverage of code statements, branches, paths, conditions.

• unit testing - the most 'micro' scale of testing; to test particular functions or code

modules. Typically done by the programmer and not by testers, as it requires detailed

knowledge of the internal program design and code. Not always easily done unless the

application has a well-designed architecture with tight code; may require developing

test driver modules or test harnesses.

• incremental integration testing - continuous testing of an application as new

functionality is added; requires that various aspects of an application's functionality be

© Copyright : IT Engg Portal – www.itportal.in 332

independent enough to work separately before all parts of the program are completed,

or that test drivers be developed as needed; done by programmers or by testers.

• integration testing - testing of combined parts of an application to determine if they

function together correctly. The 'parts' can be code modules, individual applications,

client and server applications on a network, etc. This type of testing is especially

relevant to client/server and distributed systems.

• functional testing - black-box type testing geared to functional requirements of an

application; this type of testing should be done by testers. This doesn't mean that the

programmers shouldn't check that their code works before releasing it (which of

course applies to any stage of testing.)

• system testing - black-box type testing that is based on overall requirements

specifications; covers all combined parts of a system.

• end-to-end testing - similar to system testing; the 'macro' end of the test scale;

involves testing of a complete application environment in a situation that mimics real-

world use, such as interacting with a database, using network communications, or

interacting with other hardware, applications, or systems if appropriate.

• sanity testing or smoke testing - typically an initial testing effort to determine if a

new software version is performing well enough to accept it for a major testing effort.

For example, if the new software is crashing systems every 5 minutes, bogging down

systems to a crawl, or corrupting databases, the software may not be in a 'sane' enough

condition to warrant further testing in its current state.

• regression testing - re-testing after fixes or modifications of the software or its

environment. It can be difficult to determine how much re-testing is needed, especially

near the end of the development cycle. Automated testing tools can be especially

useful for this type of testing.

• acceptance testing - final testing based on specifications of the end-user or customer,

or based on use by end-users/customers over some limited period of time.

• load testing - testing an application under heavy loads, such as testing of a web site

under a range of loads to determine at what point the system's response time degrades

or fails.

• stress testing - term often used interchangeably with 'load' and 'performance' testing.

Also used to describe such tests as system functional testing while under unusually

heavy loads, heavy repetition of certain actions or inputs, input of large numerical

values, large complex queries to a database system, etc.

• performance testing - term often used interchangeably with 'stress' and 'load' testing.

Ideally 'performance' testing (and any other 'type' of testing) is defined in requirements

documentation or QA or Test Plans.

© Copyright : IT Engg Portal – www.itportal.in 333

• usability testing - testing for 'user-friendliness'. Clearly this is subjective, and will

depend on the targeted end-user or customer. User interviews, surveys, video

recording of user sessions, and other techniques can be used. Programmers and testers

are usually not appropriate as usability testers.

• install/uninstall testing - testing of full, partial, or upgrade install/uninstall processes.

• recovery testing - testing how well a system recovers from crashes, hardware

failures, or other catastrophic problems.

• security testing - testing how well the system protects against unauthorized internal

or external access, willful damage, etc; may require sophisticated testing techniques.

• compatability testing - testing how well software performs in a particular

hardware/software/operating system/network/etc. environment.

• exploratory testing - often taken to mean a creative, informal software test that is not

based on formal test plans or test cases; testers may be learning the software as they

test it.

• ad-hoc testing - similar to exploratory testing, but often taken to mean that the testers

have significant understanding of the software before testing it.

• user acceptance testing - determining if software is satisfactory to an end-user or

customer.

• comparison testing - comparing software weaknesses and strengths to competing

products.

• alpha testing - testing of an application when development is nearing completion;

minor design changes may still be made as a result of such testing. Typically done by

end-users or others, not by programmers or testers.

• beta testing - testing when development and testing are essentially completed and

final bugs and problems need to be found before final release. Typically done by end-

users or others, not by programmers or testers.

• mutation testing - a method for determining if a set of test data or test cases is useful,

by deliberately introducing various code changes ('bugs') and retesting with the

original test data/cases to determine if the 'bugs' are detected. Proper implementation

requires large computational resources.

What are 5 common problems in the software development process? • poor requirements - if requirements are unclear, incomplete, too general, or not

testable, there will be problems.

• unrealistic schedule - if too much work is crammed in too little time, problems are

inevitable.

• inadequate testing - no one will know whether or not the program is any good until

© Copyright : IT Engg Portal – www.itportal.in 334

the customer complains or systems crash.

• featuritis - requests to pile on new features after development is underway; extremely

common.

• miscommunication - if developers don't know what's needed or customer's have

erroneous expectations, problems are guaranteed.

What are 5 common solutions to software development problems? • solid requirements - clear, complete, detailed, cohesive, attainable, testable

requirements that are agreed to by all players. Use prototypes to help nail down

requirements.

• realistic schedules - allow adequate time for planning, design, testing, bug fixing, re-

testing, changes, and documentation; personnel should be able to complete the project

without burning out.

• adequate testing - start testing early on, re-test after fixes or changes, plan for

adequate time for testing and bug-fixing.

• stick to initial requirements as much as possible - be prepared to defend against

changes and additions once development has begun, and be prepared to explain

consequences. If changes are necessary, they should be adequately reflected in related

schedule changes. If possible, use rapid prototyping during the design phase so that

customers can see what to expect. This will provide them a higher comfort level with

their requirements decisions and minimize changes later on.

• communication - require walkthroughs and inspections when appropriate; make

extensive use of group communication tools - e-mail, groupware, networked bug-

tracking tools and change management tools, intranet capabilities, etc.; insure that

documentation is available and up-to-date - preferably electronic, not paper; promote

teamwork and cooperation; use protoypes early on so that customers' expectations are

clarified.

What is software 'quality'? Quality software is reasonably bug-free, delivered on time and within budget, meets

requirements and/or expectations, and is maintainable. However, quality is obviously a

subjective term. It will depend on who the 'customer' is and their overall influence in

the scheme of things. A wide-angle view of the 'customers' of a software development

project might include end-users, customer acceptance testers, customer contract

officers, customer management, the development organization's

management/accountants/testers/salespeople, future software maintenance engineers,

stockholders, magazine columnists, etc. Each type of 'customer' will have their own

© Copyright : IT Engg Portal – www.itportal.in 335

slant on 'quality' - the accounting department might define quality in terms of profits

while an end-user might define quality as user-friendly and bug-free.

What is 'good code'?

'Good code' is code that works, is bug free, and is readable and maintainable. Some

organizations have coding 'standards' that all developers are supposed to adhere to, but

everyone has different ideas about what's best, or what is too many or too few rules.

There are also various theories and metrics, such as McCabe Complexity metrics. It

should be kept in mind that excessive use of standards and rules can stifle productivity

and creativity. 'Peer reviews', 'buddy checks' code analysis tools, etc. can be used to

check for problems and enforce standards.

For C and C++ coding, here are some typical ideas to consider in setting

rules/standards; these may or may not apply to a particular situation:

• minimize or eliminate use of global variables.

• use descriptive function and method names - use both upper and lower case, avoid

abbreviations, use as many characters as necessary to be adequately descriptive (use of

more than 20 characters is not out of line); be consistent in naming conventions.

• use descriptive variable names - use both upper and lower case, avoid abbreviations,

use as many characters as necessary to be adequately descriptive (use of more than 20

characters is not out of line); be consistent in naming conventions.

• function and method sizes should be minimized; less than 100 lines of code is good,

less than 50 lines is preferable.

• function descriptions should be clearly spelled out in comments preceding a

function's code.

• organize code for readability.

• use whitespace generously - vertically and horizontally

• each line of code should contain 70 characters max.

• one code statement per line.

• coding style should be consistent throught a program (eg, use of brackets,

indentations, naming conventions, etc.)

• in adding comments, err on the side of too many rather than too few comments; a

common rule of thumb is that there should be at least as many lines of comments

(including header blocks) as lines of code.

• no matter how small, an application should include documentaion of the overall

program function and flow (even a few paragraphs is better than nothing); or if

possible a separate flow chart and detailed program documentation.

© Copyright : IT Engg Portal – www.itportal.in 336

• make extensive use of error handling procedures and status and error logging.

• for C++, to minimize complexity and increase maintainability, avoid too many levels

of inheritance in class heirarchies (relative to the size and complexity of the

application). Minimize use of multiple inheritance, and minimize use of operator

overloading (note that the Java programming language eliminates multiple inheritance

and operator overloading.)

• for C++, keep class methods small, less than 50 lines of code per method is

preferable.

• for C++, make liberal use of exception handlers

What is 'good design'? 'Design' could refer to many things, but often refers to 'functional design' or 'internal

design'. Good internal design is indicated by software code whose overall structure is

clear, understandable, easily modifiable, and maintainable; is robust with sufficient

error-handling and status logging capability; and works correctly when implemented.

Good functional design is indicated by an application whose functionality can be

traced back to customer and end-user requirements. (See further discussion of

functional and internal design in 'What's the big deal about requirements?' in FAQ #2.)

For programs that have a user interface, it's often a good idea to assume that the end

user will have little computer knowledge and may not read a user manual or even the

on-line help; some common rules-of-thumb include:

• the program should act in a way that least surprises the user

• it should always be evident to the user what can be done next and how to exit

• the program shouldn't let the users do something stupid without warning them.

What is SEI? CMM? ISO? IEEE? ANSI? Will it help? • SEI = 'Software Engineering Institute' at Carnegie-Mellon University; initiated by

the U.S. Defense Department to help improve software development processes.

• CMM = 'Capability Maturity Model', developed by the SEI. It's a model of 5 levels

of organizational 'maturity' that determine effectiveness in delivering quality software.

It is geared to large organizations such as large U.S. Defense Department contractors.

However, many of the QA processes involved are appropriate to any organization, and

if reasonably applied can be helpful. Organizations can receive CMM ratings by

undergoing assessments by qualified auditors.

Level 1 - characterized by chaos, periodic panics, and heroic efforts required by

individuals to successfully complete projects. Few if any processes in place; successes

© Copyright : IT Engg Portal – www.itportal.in 337

may not be repeatable.

Level 2 - software project tracking, requirements management, realistic planning, and

configuration management processes are in place; successful practices can be

repeated.

Level 3 - standard software development and maintenance processes are integrated

throughout an organization; a Software Engineering Process Group is is in place to

oversee software processes, and training programs are used to ensure understanding

and compliance.

Level 4 - metrics are used to track productivity, processes, and products. Project

performance is predictable, and quality is consistently high.

Level 5 - the focus is on continouous process improvement. The impact of new

processes and technologies can be predicted and effectively implemented when

required.

Perspective on CMM ratings: During 1997-2001, 1018 organizations were assessed.

Of those, 27% were rated at Level 1, 39% at 2, 23% at 3, 6% at 4, and 5% at 5. (For

ratings during the period 1992-96, 62% were at Level 1, 23% at 2, 13% at 3, 2% at 4,

and

0.4% at 5.) The median size of organizations was 100 software

engineering/maintenance personnel; 32% of organizations were U.S. federal

contractors or agencies. For those rated at

Level 1, the most problematical key process area was in Software Quality Assurance.

• ISO = 'International Organisation for Standardization' - The ISO 9001:2000 standard

(which replaces the previous standard of 1994) concerns quality systems that are

assessed by outside auditors, and it applies to many kinds of production and

manufacturing organizations, not just software. It covers documentation, design,

development, production, testing, installation, servicing, and other processes. The full

set of standards consists of: (a)Q9001-2000 - Quality Management Systems:

Requirements; (b)Q9000-2000 - Quality Management Systems: Fundamentals and

Vocabulary; (c)Q9004-2000 - Quality Management Systems: Guidelines for

Performance Improvements. To be ISO 9001 certified, a third-party auditor assesses

an organization, and certification is typically good for about 3 years, after which a

© Copyright : IT Engg Portal – www.itportal.in 338

complete reassessment is required. Note that ISO certification does not necessarily

indicate quality products - it indicates only that documented processes are followed.

Also see http://www.iso.ch/ for the latest information. In the U.S. the standards can be

purchased via the ASQ web site at http://e-standards.asq.org/

• IEEE = 'Institute of Electrical and Electronics Engineers' - among other things,

creates standards such as 'IEEE Standard for Software Test Documentation'

(IEEE/ANSI Standard 829), 'IEEE Standard of Software Unit Testing (IEEE/ANSI

Standard 1008), 'IEEE Standard for Software Quality Assurance Plans' (IEEE/ANSI

Standard 730), and others.

• ANSI = 'American National Standards Institute', the primary industrial standards

body in the U.S.; publishes some software-related standards in conjunction with the

IEEE and ASQ (American Society for Quality).

• Other software development process assessment methods besides CMM and ISO

9000 include SPICE, Trillium, TickIT. and Bootstrap.

What is the 'software life cycle'? The life cycle begins when an application is first conceived and ends when it is no

longer in use. It includes aspects such as initial concept, requirements analysis,

functional design, internal design, documentation planning, test planning, coding,

document preparation, integration, testing, maintenance, updates, retesting, phase-out,

and other aspects.

Will automated testing tools make testing easier? • Possibly. For small projects, the time needed to learn and implement them may not

be worth it. For larger projects, or on-going long-term projects they can be valuable.

• A common type of automated tool is the 'record/playback' type. For example, a tester

could click through all combinations of menu choices, dialog box choices, buttons, etc.

in an application GUI and have them 'recorded' and the results logged by a tool. The

'recording' is typically in the form of text based on a scripting language that is

interpretable by the testing tool. If new buttons are added, or some underlying code in

the application is changed, etc. the application might then be retested by just 'playing

back' the 'recorded' actions, and comparing the logging results to check effects of the

changes. The problem with such tools is that if there are continual changes to the

system being tested, the 'recordings' may have to be changed so much that it becomes

© Copyright : IT Engg Portal – www.itportal.in 339

very time-consuming to continuously update the scripts. Additionally, interpretation

and analysis of results (screens, data, logs, etc.) can be a difficult task. Note that there

are record/playback tools for text-based interfaces also, and for all types of platforms.

• Other automated tools can include:

code analyzers - monitor code complexity, adherence to standards, etc.

coverage analyzers - these tools check which parts of the code have been exercised by

a test, and may be oriented to code statement coverage, condition coverage, path

coverage, etc.

memory analyzers - such as bounds-checkers and leak detectors.

load/performance test tools - for testing client/server and web applications under

various load

levels.

web test tools - to check that links are valid, HTML code usage is correct, client-side

and server-side programs work, a web site's interactions are secure.

other tools - for test case management, documentation management, bug reporting,

and configuration management.

====================================================================

© Copyright : IT Engg Portal – www.itportal.in 340

Microprocessor

Interview Questions &

Answers

© Copyright : IT Engg Portal – www.itportal.in 341

Microprocessor Interview Questions and Answers

What is a Microprocessor? Microprocessor is a program-controlled device, which fetches the instructions from

memory, decodes and executes the instructions. Most Micro Processor are single- chip

devices.

What are the flags in 8086? In 8086 Carry flag, Parity flag, Auxiliary carry flag, Zero flag, Overflow flag, Trace

flag, Interrupt flag, Direction flag, and Sign flag.

Why crystal is a preferred clock source? Because of high stability, large Q (Quality Factor) & the frequency that doesn‘t drift

with aging. Crystal is used as a clock source most of the times.

In 8085 which is called as High order / Low order Register? Flag is called as Low order register & Accumulator is called as High order Register.

What is Tri-state logic? Three Logic Levels are used and they are High, Low, High impedance state. The high

and low are normal logic levels & high impedance state is electrical open circuit

conditions. Tri-state logic has a third line called enable line.

What happens when HLT instruction is executed in processor? The Micro Processor enters into Halt-State and the buses are tri-stated.

Which Stack is used in 8085? LIFO (Last In First Out) stack is used in 8085.In this type of Stack the last stored

information can be retrieved first

What is Program counter? Program counter holds the address of either the first byte of the next instruction to be

fetched for execution or the address of the next byte of a multi byte instruction, which

has not been completely fetched. In both the cases it gets incremented automatically

one by one as the instruction bytes get fetched. Also Program register keeps the

address of the next instruction.

© Copyright : IT Engg Portal – www.itportal.in 342

What are the various registers in 8085? Accumulator register, Temporary register, Instruction register, Stack Pointer, Program

Counter are the various registers in 8085

What is 1st / 2nd / 3rd / 4th generation processor? The processor made of PMOS / NMOS / HMOS / HCMOS technology is called 1st /

2nd / 3rd / 4th generation processor, and it is made up of 4 / 8 / 16 / 32 bits.

Name the processor lines of two major manufacturers? High-end: Intel - Pentium (II, III, 4), AMD - Athlon. Low-end: Intel - Celeron, AMD -

Duron. 64-bit: Intel - Itanium 2, AMD - Opteron.

What‟s the speed and device maximum specs for Firewire? IEEE 1394 (Firewire) supports the maximum of 63 connected devices with speeds up

to 400 Mbps. Where‘s MBR located on the disk? Main Boot Record is located in

sector 0, track 0, head 0, cylinder 0 of the primary active partition.

Where does CPU Enhanced mode originate from? Intel‘s 80386 was the first 32-bit processor, and since the company had to backward-

support the 8086. All the modern Intel-based processors run in the Enhanced mode,

capable of switching between Real mode (just like the real 8086) and Protected mode,

which is the current mode of operation.

How many bit combinations are there in a byte? Byte contains 8 combinations of bits.

Have you studied buses? What types? There are three types of buses.

Address bus: This is used to carry the Address to the memory to fetch either

Instruction or Data.

Data bus : This is used to carry the Data from the memory.

Control bus : This is used to carry the Control signals like RD/WR, Select etc.

What is the Maximum clock frequency in 8086? 5 Mhz is the Maximum clock frequency in 8086.

What is meant by Maskable interrupts? An interrupt that can be turned off by the programmer is known as Maskable interrupt.

© Copyright : IT Engg Portal – www.itportal.in 343

What is Non-Maskable interrupts? An interrupt which can be never be turned off (ie. disabled) is known as Non-

Maskable interrupt

What are the different functional units in 8086? Bus Interface Unit and Execution unit, are the two different functional units in 8086.

What are the various segment registers in 8086? Code, Data, Stack, Extra Segment registers in 8086.

What does EU do? Execution Unit receives program instruction codes and data from BIU, executes these

instructions and store the result in general registers.

Which Stack is used in 8086? k is used in 8086? FIFO (First In First Out) stack is used in 8086.In this type of Stack the first stored

information is retrieved first.

What are the flags in 8086? In 8086 Carry flag, Parity flag, Auxiliary carry flag, Zero flag, Overflow flag, Trace

flag, Interrupt flag, Direction flag, and Sign flag.

What is SIM and RIM instructions? SIM is Set Interrupt Mask. Used to mask the hardware interrupts.

RIM is Read Interrupt Mask. Used to check whether the interrupt is Masked or not.

What is the difference between 8086 and 8088? The BIU in 8088 is 8-bit data bus & 16- bit in 8086.Instruction queue is 4 byte long in

8088and 6 byte in 8086.

Give example for Non-Maskable interrupts? Trap is known as Non-Maskable interrupts, which is used in emergency condition.

Give examples for Micro controller? Z80, Intel MSC51 &96, Motorola are the best examples of Microcontroller.

What is clock frequency for 8085? 3 MHz is the maximum clock frequency for 8085.

© Copyright : IT Engg Portal – www.itportal.in 344

Give an example of one address microprocessor? 8085 is a one address microprocessor.

Give examples for 8 / 16 / 32 bit Microprocessor? 8-bit Processor - 8085 / Z80 / 6800; 16-bit Processor - 8086 / 68000 / Z8000; 32-bit

Processor - 80386 / 80486

What is meant by a bus? A bus is a group of conducting lines that carriers data, address, & control signals.

What are the various registers in 8085? Accumulator register, Temporary register, Instruction register, Stack Pointer, Program

Counter are the various registers in 8085

Why crystal is a preferred clock source? Because of high stability, large Q (Quality Factor) & the frequency that doesn‘t drift

with aging. Crystal is used as a clock source most of the times.

In 8085 which is called as High order / Low order Register? Flag is called as Low order register & Accumulator is called as High order Register.

Name 5 different addressing modes? Immediate, Direct, Register, Register indirect, Implied addressing modes

In what way interrupts are classified in 8085? In 8085 the interrupts are classified as Hardware and Software interrupts.

What is the difference between primary & secondary storage device? In primary storage device the storage capacity is limited. It has a volatile memory. In

secondary storage device the storage capacity is larger. It is a nonvolatile memory.

Primary devices are: RAM / ROM. Secondary devices are: Floppy disc / Hard disk.

Which Stack is used in 8085? LIFO (Last In First Out) stack is used in 8085.In this type of Stack the last stored

information can be retrieved first.

What is Program counter? Program counter holds the address of either the first byte of the next instruction to be

fetched for execution or the address of the next byte of a multi byte instruction, which

© Copyright : IT Engg Portal – www.itportal.in 345

has not been completely fetched. In both the cases it gets incremented automatically

one by one as the instruction bytes get fetched. Also Program register keeps the

address of the next instruction.

What is the RST for the TRAP? RST 4.5 is called as TRAP.

What are level-triggering interrupt? RST 6.5 & RST 5.5 are level-triggering interrupts.

Which interrupt is not level-sensitive in 8085? RST 7.5 is a raising edge-triggering interrupt.

What are Software interrupts? RST0, RST1, RST2, RST3, RST4, RST5, RST6, RST7.

What are the various flags used in 8085? Sign flag, Zero flag, Auxiliary flag, Parity flag, Carry flag.

In 8085 name the 16 bit registers? Stack pointer and Program counter all have 16 bits.

What is Stack Pointer? Stack pointer is a special purpose 16-bit register in the Microprocessor, which holds

the address of the top of the stack.

What happens when HLT instruction is executed in processor? The Micro Processor enters into Halt-State and the buses are tri-stated.

What does Quality factor mean? The Quality factor is also defined, as Q. So it is a number, which reflects the lossness

of a circuit. Higher the Q, the lower are the losses.

How many interrupts are there in 8085? There are 12 interrupts in 8085.

What is Tri-state logic? Three Logic Levels are used and they are High, Low, High impedance state. The high

© Copyright : IT Engg Portal – www.itportal.in 346

and low are normal logic levels & high impedance state is electrical open circuit

conditions. Tri-state logic has a third line called enable line.

Which interrupt has the highest priority? TRAP has the highest priority

What are Hardware interrupts? TRAP, RST7.5, RST6.5, RST5.5, INTR

Can an RC circuit be used as clock source for 8085? Yes, it can be used, if an accurate clock frequency is not required. Also, the

component cost is low compared to LC or Crystal

=============================================================

© Copyright : IT Engg Portal – www.itportal.in 347

Oracle

Interview Questions

&

Answers

© Copyright : IT Engg Portal – www.itportal.in 348

Oracle Interview Questions and Answers

What are the components of physical database structure of Oracle database?

Oracle database is comprised of three types of files. One or more datafiles, two are

more redo log files, and one or more control files.

What are the components of logical database structure of Oracle database? There are tablespaces and database's schema objects.

What is a tablespace? A database is divided into Logical Storage Unit called tablespaces. A tablespace is

used to grouped related logical structures together.

What is SYSTEM tablespace and when is it created? Every Oracle database contains a tablespace named SYSTEM, which is automatically

created when the database is created. The SYSTEM tablespace always contains the

data dictionary tables for the entire database.

Explain the relationship among database, tablespace and data file ? Each databases logically divided into one or more tablespaces one or more data files

are explicitly created for each tablespace.

What is schema? A schema is collection of database objects of a user.

What are Schema Objects? Schema objects are the logical structures that directly refer to the database's data.

Schema objects include tables, views, sequences, synonyms, indexes, clusters,

database triggers, procedures, functions packages and database links.

Can objects of the same schema reside in different tablespaces? Yes.

Can a tablespace hold objects from different schemes? Yes.

What is Oracle table? A table is the basic unit of data storage in an Oracle database. The tables of a database

hold all of the user accessible data. Table data is stored in rows and columns.

© Copyright : IT Engg Portal – www.itportal.in 349

What is an Oracle view? A view is a virtual table. Every view has a query attached to it. (The query is a

SELECT statement that identifies the columns and rows of the table(s) the view uses.)

What is Partial Backup ? A Partial Backup is any operating system backup short of a full backup, taken while

the database is open or shut down.

What is Mirrored on-line Redo Log ?

A mirrored on-line redo log consists of copies of on-line redo log files physically

located on separate disks, changes made to one member of the group are made to all

members.

What is Full Backup ? A full backup is an operating system backup of all data files, on-line redo log files and

control file that constitute ORACLE database and the parameter.

Can a View based on another View ? Yes.

Can a Tablespace hold objects from different Schemes ? Yes.

Can objects of the same Schema reside in different tablespace ? Yes.

What is the use of Control File ? When an instance of an ORACLE database is started, its control file is used to identify

the database and redo log files that must be opened for database operation to proceed.

It is also used in database recovery.

Do View contain Data ? Views do not contain or store data.

What are the Referential actions supported by FOREIGN KEY integrity

constraint ? UPDATE and DELETE Restrict - A referential integrity rule that disallows the update

© Copyright : IT Engg Portal – www.itportal.in 350

or deletion of referenced data. DELETE Cascade - When a referenced row is deleted

all associated dependent rows are deleted.

What are the type of Synonyms? There are two types of Synonyms Private and Public.

What is a Redo Log ? The set of Redo Log files YSDATE,UID,USER or USERENV SQL functions, or the

pseudo columns LEVEL or ROWNUM.

What is an Index Segment ? Each Index has an Index segment that stores all of its data.

Explain the relationship among Database, Tablespace and Data file? Each databases logically divided into one or more tablespaces one or more data files

are explicitly created for each tablespace

What are the different type of Segments ? Data Segment, Index Segment, Rollback Segment and Temporary Segment.

What are Clusters ? Clusters are groups of one or more tables physically stores together to share common

columns and are often used together.

What is an Integrity Constrains ? An integrity constraint is a declarative way to define a business rule for a column of a

table.

What is an Index ? An Index is an optional structure associated with a table to have direct access to rows,

which can be created to increase the performance of data retrieval. Index can be

created on one or more columns of a table.

What is an Extent ? An Extent is a specific number of contiguous data blocks, obtained in a single

allocation, and used to store a specific type of information.

© Copyright : IT Engg Portal – www.itportal.in 351

What is a View ? A view is a virtual table. Every view has a Query attached to it. (The Query is a

SELECT statement that identifies the columns and rows of the table(s) the view uses.)

What is Table ? A table is the basic unit of data storage in an ORACLE database. The tables of a

database hold all of the user accessible data. Table data is stored in rows and columns.

Can a view based on another view?

Yes.

What are the advantages of views? - Provide an additional level of table security, by restricting access to a predetermined

set of rows and columns of a table.

- Hide data complexity.

- Simplify commands for the user.

- Present the data in a different perspective from that of the base table.

- Store complex queries.

What is an Oracle sequence? A sequence generates a serial list of unique numbers for numerical columns of a

database's tables.

What is a synonym? A synonym is an alias for a table, view, sequence or program unit.

What are the types of synonyms? There are two types of synonyms private and public.

What is a private synonym? Only its owner can access a private synonym.

What is a public synonym? Any database user can access a public synonym.

What are synonyms used for? - Mask the real name and owner of an object.

- Provide public access to an object

- Provide location transparency for tables, views or program units of a remote

© Copyright : IT Engg Portal – www.itportal.in 352

database.

- Simplify the SQL statements for database users.

What is an Oracle index? An index is an optional structure associated with a table to have direct access to rows,

which can be created to increase the performance of data retrieval. Index can be

created on one or more columns of a table.

How are the index updates? Indexes are automatically maintained and used by Oracle. Changes to table data are

automatically incorporated into all relevant indexes.

What is a Tablespace? A database is divided into Logical Storage Unit called tablespace. A tablespace is used

to grouped related logical structures together

What is Rollback Segment ? A Database contains one or more Rollback Segments to temporarily store "undo"

information.

What are the Characteristics of Data Files ? A data file can be associated with only one database. Once created a data file can't

change size. One or more data files form a logical unit of database storage called a

tablespace.

How to define Data Block size ? A data block size is specified for each ORACLE database when the database is

created. A database users and allocated free database space in ORACLE data blocks.

Block size is specified in INIT.ORA file and can‘t be changed latter.

What does a Control file Contain ? A Control file records the physical structure of the database. It contains the following

information.

Database Name

Names and locations of a database's files and redolog files.

Time stamp of database creation.

What is difference between UNIQUE constraint and PRIMARY KEY constraint

?

© Copyright : IT Engg Portal – www.itportal.in 353

A column defined as UNIQUE can contain Nulls while a column defined as

PRIMARY KEY can't contain Nulls.

What is Index Cluster ? A Cluster with an index on the Cluster Key

When does a Transaction end ? When it is committed or Rollbacked.

What is the effect of setting the value "ALL_ROWS" for OPTIMIZER_GOAL

parameter of the ALTER SESSION command ? What are the factors that affect

OPTIMIZER in choosing an Optimization approach ? Answer The OPTIMIZER_MODE initialization parameter Statistics in the Data

Dictionary the OPTIMIZER_GOAL parameter of the ALTER SESSION command

hints in the statement.

What is the effect of setting the value "CHOOSE" for OPTIMIZER_GOAL,

parameter of the ALTER SESSION Command ? The Optimizer chooses Cost_based approach and optimizes with the goal of best

throughput if statistics for atleast one of the tables accessed by the SQL statement exist

in the data dictionary. Otherwise the OPTIMIZER chooses RULE_based approach.

How does one create a new database? (for DBA) One can create and modify Oracle databases using the Oracle "dbca" (Database

Configuration Assistant) utility. The dbca utility is located in the

$ORACLE_HOME/bin directory. The Oracle Universal Installer (oui) normally starts

it after installing the database server software.

One can also create databases manually using scripts. This option, however, is falling

out of fashion, as it is quite involved and error prone. Look at this example for creating

and Oracle 9i database:

CONNECT SYS AS SYSDBA

ALTER SYSTEM SET DB_CREATE_FILE_DEST='/u01/oradata/';

ALTER SYSTEM SET DB_CREATE_ONLINE_LOG_DEST_1='/u02/oradata/';

ALTER SYSTEM SET DB_CREATE_ONLINE_LOG_DEST_2='/u03/oradata/';

CREATE DATABASE;

What database block size should I use? (for DBA) Oracle recommends that your database block size match, or be multiples of your

© Copyright : IT Engg Portal – www.itportal.in 354

operating system block size. One can use smaller block sizes, but the performance cost

is significant. Your choice should depend on the type of application you are running. If

you have many small transactions as with OLTP, use a smaller block size. With fewer

but larger transactions, as with a DSS application, use a larger block size. If you are

using a volume manager, consider your "operating system block size" to be 8K. This is

because volume manager products use 8K blocks (and this is not configurable).

What are the different approaches used by Optimizer in choosing an execution

plan ? Rule-based and Cost-based.

What does ROLLBACK do ? ROLLBACK retracts any of the changes resulting from the SQL statements in the

transaction.

How does one coalesce free space ? (for DBA) SMON coalesces free space (extents) into larger, contiguous extents every 2 hours and

even then, only for a short period of time.

SMON will not coalesce free space if a tablespace's default storage parameter

"pctincrease" is set to 0. With Oracle 7.3 one can manually coalesce a tablespace using

the ALTER TABLESPACE ... COALESCE; command, until then use:

SQL> alter session set events 'immediate trace name coalesce level n';

Where 'n' is the tablespace number you get from SELECT TS#, NAME FROM

SYS.TS$;

You can get status information about this process by selecting from the

SYS.DBA_FREE_SPACE_COALESCED dictionary view.

How does one prevent tablespace fragmentation? (for DBA) Always set PCTINCREASE to 0 or 100.

Bizarre values for PCTINCREASE will contribute to fragmentation. For example if

you set PCTINCREASE to 1 you will see that your extents are going to have weird

and wacky sizes: 100K, 100K, 101K, 102K, etc. Such extents of bizarre size are rarely

re-used in their entirety. PCTINCREASE of 0 or 100 gives you nice round extent sizes

that can easily be reused. E.g.. 100K, 100K, 200K, 400K, etc.

Use the same extent size for all the segments in a given tablespace. Locally Managed

tablespaces (available from 8i onwards) with uniform extent sizes virtually eliminates

any tablespace fragmentation. Note that the number of extents per segment does not

© Copyright : IT Engg Portal – www.itportal.in 355

cause any performance issue anymore, unless they run into thousands and thousands

where additional I/O may be required to fetch the additional blocks where extent maps

of the segment are stored.

Where can one find the high water mark for a table? (for DBA) There is no single system table, which contains the high water mark (HWM) for a

table. A table's HWM can be calculated using the results from the following SQL

statements:

SELECT BLOCKS

FROM DBA_SEGMENTS

WHERE OWNER=UPPER(owner) AND SEGMENT_NAME = UPPER(table);

ANALYZE TABLE owner.table ESTIMATE STATISTICS;

SELECT EMPTY_BLOCKS

FROM DBA_TABLES

WHERE OWNER=UPPER(owner) AND SEGMENT_NAME = UPPER(table);

Thus, the tables' HWM = (query result 1) - (query result 2) - 1

NOTE: You can also use the DBMS_SPACE package and calculate the HWM =

TOTAL_BLOCKS - UNUSED_BLOCKS - 1.

What is COST-based approach to optimization ? Considering available access paths and determining the most efficient execution plan

based on statistics in the data dictionary for the tables accessed by the statement and

their associated clusters and indexes.

What does COMMIT do ? COMMIT makes permanent the changes resulting from all SQL statements in the

transaction. The changes made by the SQL statements of a transaction become visible

to other user sessions transactions that start only after transaction is committed.

How are extents allocated to a segment? (for DBA) Oracle8 and above rounds off extents to a multiple of 5 blocks when more than 5

blocks are requested. If one requests 16K or 2 blocks (assuming a 8K block size),

Oracle doesn't round it up to 5 blocks, but it allocates 2 blocks or 16K as requested. If

one asks for 8 blocks, Oracle will round it up to 10 blocks.

Space allocation also depends upon the size of contiguous free space available. If one

asks for 8 blocks and Oracle finds a contiguous free space that is exactly 8 blocks, it

would give it you. If it were 9 blocks, Oracle would also give it to you. Clearly Oracle

doesn't always round extents to a multiple of 5 blocks.

© Copyright : IT Engg Portal – www.itportal.in 356

The exception to this rule is locally managed tablespaces. If a tablespace is created

with local extent management and the extent size is 64K, then Oracle allocates 64K or

8 blocks assuming 8K-block size. Oracle doesn't round it up to the multiple of 5 when

a tablespace is locally managed.

Can one rename a database user (schema)? (for DBA) No, this is listed as Enhancement Request 158508. Workaround:

Do a user-level export of user A

create new user B

Import system/manager fromuser=A touser=B

Drop user A

Define Transaction ?

A Transaction is a logical unit of work that comprises one or more SQL statements

executed by a single user.

What is Read-Only Transaction ? A Read-Only transaction ensures that the results of each query executed in the

transaction are consistant with respect to the same point in time.

What is a deadlock ? Explain .

Two processes wating to update the rows of a table which are locked by the other

process then deadlock arises. In a database environment this will often happen because

of not issuing proper row lock commands. Poor design of front-end application may

cause this situation and the performance of server will reduce drastically.

These locks will be released automatically when a commit/rollback operation

performed or any one of this processes being killed externally.

What is a Schema ? The set of objects owned by user account is called the schema.

What is a cluster Key ? The related columns of the tables are called the cluster key. The cluster key is indexed

using a cluster index and its value is stored only once for multiple tables in the cluster.

What is Parallel Server ? Multiple instances accessing the same database (Only In Multi-CPU environments)

© Copyright : IT Engg Portal – www.itportal.in 357

What are the basic element of Base configuration of an oracle Database ? It consists of

one or more data files.

one or more control files.

two or more redo log files.

The Database contains

multiple users/schemas

one or more rollback segments

one or more tablespaces

Data dictionary tables

User objects (table,indexes,views etc.,)

The server that access the database consists of

SGA (Database buffer, Dictionary Cache Buffers, Redo log buffers, Shared SQL pool)

SMON (System MONito)

PMON (Process MONitor)

LGWR (LoG Write)

DBWR (Data Base Write)

ARCH (ARCHiver)

CKPT (Check Point)

RECO

Dispatcher

User Process with associated PGS

What is clusters ? Group of tables physically stored together because they share common columns and

are often used together is called Cluster.

What is an Index ? How it is implemented in Oracle Database ? An index is a database structure used by the server to have direct access of a row in a

table. An index is automatically created when a unique of primary key constraint

clause is specified in create table comman (Ver 7.0)

What is a Database instance ? Explain A database instance (Server) is a set of memory structure and background processes

that access a set of database files.

The process can be shared by all users. The memory structure that are used to store

© Copyright : IT Engg Portal – www.itportal.in 358

most queried data from database. This helps up to improve database performance by

decreasing the amount of I/O performed against data file.

What is the use of ANALYZE command ? To perform one of these function on an index, table, or cluster:

- To collect statistics about object used by the optimizer and store them in the data

dictionary.

- To delete statistics about the object used by object from the data dictionary.

- To validate the structure of the object.

- To identify migrated and chained rows of the table or cluster.

What is default tablespace ? The Tablespace to contain schema objects created without specifying a tablespace

name.

What are the system resources that can be controlled through Profile ? The number of concurrent sessions the user can establish the CPU processing time

available to the user's session the CPU processing time available to a single call to

ORACLE made by a SQL statement the amount of logical I/O available to the user's

session the amout of logical I/O available to a single call to ORACLE made by a SQL

statement the allowed amount of idle time for the user's session the allowed amount of

connect time for the user's session.

What is Tablespace Quota ? The collective amount of disk space available to the objects in a schema on a

particular tablespace.

What are the different Levels of Auditing ? Statement Auditing, Privilege Auditing and Object Auditing.

What is Statement Auditing ? Statement auditing is the auditing of the powerful system privileges without regard to

specifically named objects.

What are the database administrators utilities available ? SQL * DBA - This allows DBA to monitor and control an ORACLE database. SQL *

Loader - It loads data from standard operating system files (Flat files) into ORACLE

© Copyright : IT Engg Portal – www.itportal.in 359

database tables. Export (EXP) and Import (imp) utilities allow you to move existing

data in ORACLE format to and from ORACLE database.

How can you enable automatic archiving ? Shut the database

Backup the database

Modify/Include LOG_ARCHIVE_START_TRUE in init.ora file.

Start up the database.

What are roles? How can we implement roles ? Roles are the easiest way to grant and manage common privileges needed by different

groups of database users. Creating roles and assigning provides to roles. Assign each

role to group of users. This will simplify the job of assigning privileges to individual

users.

What are Roles ? Roles are named groups of related privileges that are granted to users or other roles.

What are the use of Roles ? REDUCED GRANTING OF PRIVILEGES - Rather than explicitly granting the same

set of privileges to many users a database administrator can grant the privileges for a

group of related users granted to a role and then grant only the role to each member of

the group.

DYNAMIC PRIVILEGE MANAGEMENT - When the privileges of a group must

change, only the privileges of the role need to be modified. The security domains of all

users granted the group's role automatically reflect the changes made to the role.

SELECTIVE AVAILABILITY OF PRIVILEGES - The roles granted to a user can be

selectively enable (available for use) or disabled (not available for use). This allows

specific control of a user's privileges in any given situation.

APPLICATION AWARENESS - A database application can be designed to

automatically enable and disable selective roles when a user attempts to use the

application.

What is Privilege Auditing ? Privilege auditing is the auditing of the use of powerful system privileges without

regard to specifically named objects.

© Copyright : IT Engg Portal – www.itportal.in 360

What is Object Auditing ?

Object auditing is the auditing of accesses to specific schema objects without regard to

user.

What is Auditing ? Monitoring of user access to aid in the investigation of database use.

How does one see the uptime for a database? (for DBA )

Look at the following SQL query:

SELECT to_char (startup_time,'DD-MON-YYYY HH24: MI: SS') "DB Startup Time"

FROM sys.v_$instance;

Marco Bergman provided the following alternative solution:

SELECT to_char (logon_time,'Dy dd Mon HH24: MI: SS') "DB Startup Time"

FROM sys.v_$session

WHERE Sid=1 /* this is pmon */

/

Users still running on Oracle 7 can try one of the following queries:

Column STARTED format a18 head 'STARTUP TIME'

Select C.INSTANCE,

to_date (JUL.VALUE, 'J')

|| to_char (floor (SEC.VALUE/3600), '09')

|| ':'

-- || Substr (to_char (mod (SEC.VALUE/60, 60), '09'), 2, 2)

|| Substr (to_char (floor (mod (SEC.VALUE/60, 60)), '09'), 2, 2)

|| '.'

|| Substr (to_char (mod (SEC.VALUE, 60), '09'), 2, 2) STARTED

from SYS.V_$INSTANCE JUL,

SYS.V_$INSTANCE SEC,

SYS.V_$THREAD C

Where JUL.KEY like '%JULIAN%'

and SEC.KEY like '%SECOND%';

Select to_date (JUL.VALUE, 'J')

|| to_char (to_date (SEC.VALUE, 'SSSSS'), ' HH24:MI:SS') STARTED

from SYS.V_$INSTANCE JUL,

SYS.V_$INSTANCE SEC

where JUL.KEY like '%JULIAN%'

and SEC.KEY like '%SECOND%';

© Copyright : IT Engg Portal – www.itportal.in 361

select to_char (to_date (JUL.VALUE, 'J') + (SEC.VALUE/86400), -Return a DATE

'DD-MON-YY HH24:MI:SS') STARTED

from V$INSTANCE JUL,

V$INSTANCE SEC

where JUL.KEY like '%JULIAN%'

and SEC.KEY like '%SECOND%';

Where are my TEMPFILES, I don't see them in V$DATAFILE or

DBA_DATA_FILE? (for DBA ) Tempfiles, unlike normal datafiles, are not listed in v$datafile or dba_data_files.

Instead query v$tempfile or dba_temp_files:

SELECT * FROM v$tempfile;

SELECT * FROM dba_temp_files;

How do I find used/free space in a TEMPORARY tablespace? (for DBA ) Unlike normal tablespaces, true temporary tablespace information is not listed in

DBA_FREE_SPACE. Instead use the V$TEMP_SPACE_HEADER view:

SELECT tablespace_name, SUM (bytes used), SUM (bytes free)

FROM V$temp_space_header

GROUP BY tablespace_name;

What is a profile ? Each database user is assigned a Profile that specifies limitations on various system

resources available to the user.

How will you enforce security using stored procedures? Don't grant user access directly to tables within the application. Instead grant the

ability to access the procedures that access the tables. When procedure executed it will

execute the privilege of procedures owner. Users cannot access tables except via the

procedure.

How can one see who is using a temporary segment? (for DBA ) For every user using temporary space, there is an entry in SYS.V$_LOCK with type

'TS'.

All temporary segments are named 'ffff.bbbb' where 'ffff' is the file it is in and 'bbbb' is

first block of the segment. If your temporary tablespace is set to TEMPORARY, all

sorts are done in one large temporary segment. For usage stats, see

SYS.V_$SORT_SEGMENT

© Copyright : IT Engg Portal – www.itportal.in 362

From Oracle 8.0, one can just query SYS.v$sort_usage. Look at these examples:

select s.username, u."USER", u.tablespace, u.contents, u.extents, u.blocks

from sys.v_$session s, sys.v_$sort_usage u

where s.addr = u.session_addr

/

select s.osuser, s.process, s.username, s.serial#,

Sum (u.blocks)*vp.value/1024 sort_size

from sys.v_$session s, sys.v_$sort_usage u, sys.v_$parameter VP

where s.saddr = u.session_addr

and vp.name = 'db_block_size'

and s.osuser like '&1'

group by s.osuser, s.process, s.username, s.serial#, vp.value

/

How does one get the view definition of fixed views/tables? Query v$fixed_view_definition. Example: SELECT * FROM

v$fixed_view_definition WHERE view_name='V$SESSION';

What are the dictionary tables used to monitor a database spaces ? DBA_FREE_SPACE

DBA_SEGMENTS

DBA_DATA_FILES.

How can we specify the Archived log file name format and destination? By setting the following values in init.ora file. LOG_ARCHIVE_FORMAT = arch

%S/s/T/tarc (%S - Log sequence number and is zero left paded, %s - Log sequence

number not padded. %T - Thread number lef-zero-paded and %t - Thread number not

padded). The file name created is arch 0001 are if %S is used.

LOG_ARCHIVE_DEST = path.

What is user Account in Oracle database? An user account is not a physical structure in Database but it is having important

relationship to the objects in the database and will be having certain privileges.

When will the data in the snapshot log be used? We must be able to create a after row trigger on table (i.e., it should be not be already

available) After giving table privileges. We cannot specify snapshot log name because

oracle uses the name of the master table in the name of the database objects that

© Copyright : IT Engg Portal – www.itportal.in 363

support its snapshot log. The master table name should be less than or equal to 23

characters. (The table name created will be MLOGS_tablename, and trigger name will

be TLOGS name).

What dynamic data replication? Updating or Inserting records in remote database through database triggers. It may fail

if remote database is having any problem.

What is Two-Phase Commit ? Two-phase commit is mechanism that guarantees a distributed transaction either

commits on all involved nodes or rolls back on all involved nodes to maintain data

consistency across the global distributed database. It has two phase, a Prepare Phase

and a Commit Phase.

How can you Enforce Referential Integrity in snapshots ? Time the references to occur when master tables are not in use. Peform the reference

the manually immdiately locking the master tables. We can join tables in snopshots by

creating a complex snapshots that will based on the master tables.

What is a SQL * NET? SQL *NET is ORACLE's mechanism for interfacing with the communication

protocols used by the networks that facilitate distributed processing and distributed

databases. It is used in Clint-Server and Server-Server communications.

What is a SNAPSHOT ? Snapshots are read-only copies of a master table located on a remote node which is

periodically refreshed to reflect changes made to the master table.

What is the mechanism provided by ORACLE for table replication ? Snapshots and SNAPSHOT LOGs

What is snapshots? Snapshot is an object used to dynamically replicate data between distribute database at

specified time intervals. In ver 7.0 they are read only.

What are the various type of snapshots? Simple and Complex.

© Copyright : IT Engg Portal – www.itportal.in 364

Describe two phases of Two-phase commit ? Prepare phase - The global coordinator (initiating node) ask a participants to prepare

(to promise to commit or rollback the transaction, even if there is a failure) Commit -

Phase - If all participants respond to the coordinator that they are prepared, the

coordinator asks all nodes to commit the transaction, if all participants cannot prepare,

the coordinator asks all nodes to roll back the transaction.

What is snapshot log ? It is a table that maintains a record of modifications to the master table in a snapshot. It

is stored in the same database as master table and is only available for simple

snapshots. It should be created before creating snapshots.

What are the benefits of distributed options in databases? Database on other servers can be updated and those transactions can be grouped

together with others in a logical unit.

Database uses a two phase commit.

What are the options available to refresh snapshots ? COMPLETE - Tables are completely regenerated using the snapshots query and the

master tables every time the snapshot referenced.

FAST - If simple snapshot used then a snapshot log can be used to send the changes to

the snapshot tables.

FORCE - Default value. If possible it performs a FAST refresh; Otherwise it will

perform a complete refresh.

What is a SNAPSHOT LOG ? A snapshot log is a table in the master database that is associated with the master table.

ORACLE uses a snapshot log to track the rows that have been updated in the master

table. Snapshot logs are used in updating the snapshots based on the master table.

What is Distributed database ? A distributed database is a network of databases managed by multiple database servers

that appears to a user as single logical database. The data of all databases in the

distributed database can be simultaneously accessed and modified.

How can we reduce the network traffic? - Replication of data in distributed environment.

© Copyright : IT Engg Portal – www.itportal.in 365

- Using snapshots to replicate data.

- Using remote procedure calls.

Differentiate simple and complex, snapshots ? - A simple snapshot is based on a query that does not contains GROUP BY clauses,

CONNECT BY clauses, JOINs, sub-query or snashot of operations.

- A complex snapshots contain atleast any one of the above.

What are the Built-ins used for sending Parameters to forms? You can pass parameter values to a form when an application executes the call_form,

New_form, Open_form or Run_product.

Can you have more than one content canvas view attached with a window? Yes. Each window you create must have atleast one content canvas view assigned to

it. You can also create a window that has manipulated content canvas view. At run

time only one of the content canvas views assign to a window is displayed at a time.

Is the After report trigger fired if the report execution fails? Yes.

Does a Before form trigger fire when the parameter form is suppressed? Yes.

What is SGA?

The System Global Area in an Oracle database is the area in memory to facilitate the

transfer of information between users. It holds the most recently requested structural

information between users. It holds the most recently requested structural information

about the database. The structure is database buffers, dictionary cache, redo log buffer

and shared pool area.

What is a shared pool? The data dictionary cache is stored in an area in SGA called the shared pool. This will

allow sharing of parsed SQL statements among concurrent users.

What is mean by Program Global Area (PGA)?

It is area in memory that is used by a single Oracle user process.

© Copyright : IT Engg Portal – www.itportal.in 366

What is a data segment? Data segment are the physical areas within a database block in which the data

associated with tables and clusters are stored.

What are the factors causing the reparsing of SQL statements in SGA? Due to insufficient shared pool size.

Monitor the ratio of the reloads takes place while executing SQL statements. If the

ratio is greater than 1 then increase the SHARED_POOL_SIZE.

What are clusters? Clusters are groups of one or more tables physically stores together to share common

columns and are often used together.

What is cluster key? The related columns of the tables in a cluster are called the cluster key.

Do a view contain data? Views do not contain or store data.

What is user Account in Oracle database? A user account is not a physical structure in database but it is having important

relationship to the objects in the database and will be having certain privileges.

How will you enforce security using stored procedures? Don't grant user access directly to tables within the application. Instead grant the

ability to access the procedures that access the tables. When procedure executed it will

execute the privilege of procedures owner. Users cannot access tables except via the

procedure.

What are the dictionary tables used to monitor a database space? DBA_FREE_SPACE

DBA_SEGMENTS

DBA_DATA_FILES.

Can a property clause itself be based on a property clause? Yes

If a parameter is used in a query without being previously defined, what diff.

exist between. report 2.0 and 2.5 when the query is applied?

© Copyright : IT Engg Portal – www.itportal.in 367

While both reports 2.0 and 2.5 create the parameter, report 2.5 gives a message that a

bind parameter has been created.

What are the sql clauses supported in the link property sheet? Where start with having.

What is trigger associated with the timer? When-timer-expired.

What are the trigger associated with image items? When-image-activated fires when the operators double clicks on an image itemwhen-

image-pressed fires when an operator clicks or double clicks on an image item

What are the different windows events activated at runtimes? When_window_activated

When_window_closed

When_window_deactivated

When_window_resized

Within this triggers, you can examine the built in system variable system.

event_window to determine the name of the window for which the trigger fired.

When do you use data parameter type? When the value of a data parameter being passed to a called product is always the

name of the record group defined in the current form. Data parameters are used to pass

data to products invoked with the run_product built-in subprogram.

What is difference between open_form and call_form? when one form invokes another form by executing open_form the first form remains

displayed, and operators can navigate between the forms as desired. when one form

invokes another form by executing call_form, the called form is modal with respect to

the calling form. That is, any windows that belong to the calling form are disabled, and

operators cannot navigate to them until they first exit the called form.

What is new_form built-in? When one form invokes another form by executing new_form oracle form exits the

first form and releases its memory before loading the new form calling new form

completely replace the first with the second. If there are changes pending in the first

form, the operator will be prompted to save them before the new form is loaded.

© Copyright : IT Engg Portal – www.itportal.in 368

What is the "LOV of Validation" Property of an item? What is the use of it? When LOV for Validation is set to True, Oracle Forms compares the current value of

the text item to the values in the first column displayed in the LOV. Whenever the

validation event occurs. If the value in the text item matches one of the values in the

first column of the LOV, validation succeeds, the LOV is not displayed, and

processing continues normally. If the value in the text item does not match one of the

values in the first column of the LOV, Oracle Forms displays the LOV and uses the

text item value as the search criteria to automatically reduce the list.

What is the diff. when Flex mode is mode on and when it is off? When flex mode is on, reports automatically resizes the parent when the child is

resized.

What is the diff. when confine mode is on and when it is off? When confine mode is on, an object cannot be moved outside its parent in the layout.

What are visual attributes? Visual attributes are the font, color, pattern proprieties that you set for form and menu

objects that appear in your application interface.

Which of the two views should objects according to possession? view by structure.

What are the two types of views available in the object navigator(specific to

report 2.5)? View by structure and view by type .

What are the vbx controls? Vbx control provide a simple method of building and enhancing user interfaces. The

controls can use to obtain user inputs and display program outputs.vbx control where

originally develop as extensions for the ms visual basic environments and include such

items as sliders, rides and knobs.

What is the use of transactional triggers? Using transactional triggers we can control or modify the default functionality of the

oracle forms.

How do you create a new session while open a new form? Using open_form built-in setting the session option Ex. Open_form('Stocks ',active,

© Copyright : IT Engg Portal – www.itportal.in 369

session). when invoke the multiple forms with open form and call_form in the same

application, state whether the following are true/False

What are the ways to monitor the performance of the report? Use reports profile executable statement. Use SQL trace facility.

If two groups are not linked in the data model editor, What is the hierarchy

between them? Two group that is above are the left most rank higher than the group that is to right or

below it.

An open form can not be execute the call_form procedure if you chain of called

forms has been initiated by another open form?

True

Explain about horizontal, Vertical tool bar canvas views? Tool bar canvas views are used to create tool bars for individual windows. Horizontal

tool bars are display at the top of a window, just under its menu bar. Vertical Tool bars

are displayed along the left side of a window

What is the purpose of the product order option in the column property sheet? To specify the order of individual group evaluation in a cross products.

What is the use of image_zoom built-in? To manipulate images in image items.

How do you reference a parameter indirectly? To indirectly reference a parameter use the NAME IN, COPY 'built-ins to indirectly

set and reference the parameters value' Example name_in ('capital parameter my

param'), Copy ('SURESH','Parameter my_param')

What is a timer? Timer is an "internal time clock" that you can programmatically create to perform an

action each time the times.

What are the two phases of block coordination? There are two phases of block coordination: the clear phase and the population phase.

During, the clear phase, Oracle Forms navigates internally to the detail block and

flushes the obsolete detail records. During the population phase, Oracle Forms issues a

© Copyright : IT Engg Portal – www.itportal.in 370

SELECT statement to repopulate the detail block with detail records associated with

the new master record. These operations are accomplished through the execution of

triggers.

What are Most Common types of Complex master-detail relationships? There are three most common types of complex master-detail relationships:

master with dependent details

master with independent details

detail with two masters

What is a text list? The text list style list item appears as a rectangular box which displays the fixed

number of values. When the text list contains values that can not be displayed, a

vertical scroll bar appears, allowing the operator to view and select undisplayed

values.

What is term? The term is terminal definition file that describes the terminal form which you are

using r20run.

What is use of term? The term file which key is correspond to which oracle report functions.

What is pop list? The pop list style list item appears initially as a single field (similar to a text item

field). When the operator selects the list icon, a list of available choices appears.

What is the maximum no of chars the parameter can store? The maximum no of chars the parameter can store is only valid for char parameters,

which can be upto 64K. No parameters default to 23Bytes and Date parameter default

to 7Bytes.

What are the default extensions of the files created by library module? The default file extensions indicate the library module type and storage format .pll -

pl/sql library module binary

What are the Coordination Properties in a Master-Detail relationship? The coordination properties are

Deferred

© Copyright : IT Engg Portal – www.itportal.in 371

Auto-Query

These Properties determine when the population phase of block

coordination should occur.

How do you display console on a window ? The console includes the status line and message line, and is displayed at the bottom of

the window to which it is assigned.To specify that the console should be displayed, set

the console window form property to the name of any window in the form. To include

the console, set console window to Null.

What are the different Parameter types? Text ParametersData Parameters

State any three mouse events system variables? System.mouse_button_pressedSystem.mouse_button_shift

What are the types of calculated columns available? Summary, Formula, Placeholder column.

Explain about stacked canvas views? Stacked canvas view is displayed in a window on top of, or "stacked" on the content

canvas view assigned to that same window. Stacked canvas views obscure some part

of the underlying content canvas view, and or often shown and hidden

programmatically.

How does one do off-line database backups? (for DBA ) Shut down the database from sqlplus or server manager. Backup all files to secondary

storage (eg. tapes). Ensure that you backup all data files, all control files and all log

files. When completed, restart your database.

Do the following queries to get a list of all files that needs to be backed up:

select name from sys.v_$datafile;

select member from sys.v_$logfile;

select name from sys.v_$controlfile;

Sometimes Oracle takes forever to shutdown with the "immediate" option. As

workaround to this problem, shutdown using these commands:

alter system checkpoint;

shutdown abort

startup restrict

© Copyright : IT Engg Portal – www.itportal.in 372

shutdown immediate

Note that if you database is in ARCHIVELOG mode, one can still use archived log

files to roll forward from an off-line backup. If you cannot take your database down

for a cold (off-line) backup at a convenient time, switch your database into

ARCHIVELOG mode and perform hot (on-line) backups.

What is the difference between SHOW_EDITOR and EDIT_TEXTITEM? Show editor is the generic built-in which accepts any editor name and takes some

input string and returns modified output string. Whereas the edit_textitem built-in

needs the input focus to be in the text item before the built-in is executed.

What are the built-ins that are used to Attach an LOV programmatically to an

item? set_item_property

get_item_property

(by setting the LOV_NAME property)

How does one do on-line database backups? (for DBA ) Each tablespace that needs to be backed-up must be switched into backup mode before

copying the files out to secondary storage (tapes). Look at this simple example.

ALTER TABLESPACE xyz BEGIN BACKUP;

! cp xyfFile1 /backupDir/

ALTER TABLESPACE xyz END BACKUP;

It is better to backup tablespace for tablespace than to put all tablespaces in backup

mode. Backing them up separately incurs less overhead. When done, remember to

backup your control files. Look at this example:

ALTER SYSTEM SWITCH LOGFILE; -- Force log switch to update control file

headers

ALTER DATABASE BACKUP CONTROLFILE TO '/backupDir/control.dbf';

NOTE: Do not run on-line backups during peak processing periods. Oracle will write

complete database blocks instead of the normal deltas to redo log files while in backup

mode. This will lead to excessive database archiving and even database freezes.

How does one backup a database using RMAN? (for DBA ) The biggest advantage of RMAN is that it only backup used space in the database.

Rman doesn't put tablespaces in backup mode, saving on redo generation overhead.

RMAN will re-read database blocks until it gets a consistent image of it. Look at this

simple backup example.

© Copyright : IT Engg Portal – www.itportal.in 373

rman target sys/*** nocatalog

run {

allocate channel t1 type disk;

backup

format '/app/oracle/db_backup/%d_t%t_s%s_p%p'

( database );

release channel t1;

}

Example RMAN restore:

rman target sys/*** nocatalog

run {

allocate channel t1 type disk;

# set until time 'Aug 07 2000 :51';

restore tablespace users;

recover tablespace users;

release channel t1;

}

The examples above are extremely simplistic and only useful for illustrating basic

concepts. By default Oracle uses the database controlfiles to store information about

backups. Normally one would rather setup a RMAN catalog database to store RMAN

metadata in. Read the Oracle Backup and Recovery Guide before implementing any

RMAN backups.

Note: RMAN cannot write image copies directly to tape. One needs to use a third-

party media manager that integrates with RMAN to backup directly to tape.

Alternatively one can backup to disk and then manually copy the backups to tape.

What are the different file extensions that are created by oracle reports? Rep file and Rdf file.

What is strip sources generate options? Removes the source code from the library file and generates a library files that

contains only pcode. The resulting file can be used for final deployment, but can not

be subsequently edited in the designer.ex. f45gen module=old_lib.pll

userid=scott/tiger strip_source YES output_file

How does one put a database into ARCHIVELOG mode? (for DBA ) The main reason for running in archivelog mode is that one can provide 24-hour

© Copyright : IT Engg Portal – www.itportal.in 374

availability and guarantee complete data recoverability. It is also necessary to enable

ARCHIVELOG mode before one can start to use on-line database backups. To enable

ARCHIVELOG mode, simply change your database startup command script, and

bounce the database:

SQLPLUS> connect sys as sysdba

SQLPLUS> startup mount exclusive;

SQLPLUS> alter database archivelog;

SQLPLUS> archive log start;

SQLPLUS> alter database open;

NOTE1: Remember to take a baseline database backup right after enabling archivelog

mode. Without it one would not be able to recover. Also, implement an archivelog

backup to prevent the archive log directory from filling-up.

NOTE2: ARCHIVELOG mode was introduced with Oracle V6, and is essential for

database point-in-time recovery. Archiving can be used in combination with on-line

and off-line database backups.

NOTE3: You may want to set the following INIT.ORA parameters when enabling

ARCHIVELOG mode: log_archive_start=TRUE, log_archive_dest=... and

log_archive_format=...

NOTE4: You can change the archive log destination of a database on-line with the

ARCHIVE LOG START TO 'directory'; statement. This statement is often used to

switch archiving between a set of directories.

NOTE5: When running Oracle Real Application Server (RAC), you need to shut down

all nodes before changing the database to ARCHIVELOG mode.

What is the basic data structure that is required for creating an LOV? Record Group.

How does one backup archived log files? (for DBA ) One can backup archived log files using RMAN or any operating system backup

utility. Remember to delete files after backing them up to prevent the archive log

directory from filling up. If the archive log directory becomes full, your database will

hang! Look at this simple RMAN backup script:

RMAN> run {

2> allocate channel dev1 type disk;

3> backup

4> format '/app/oracle/arch_backup/log_t%t_s%s_p%p'

5> (archivelog all delete input);

© Copyright : IT Engg Portal – www.itportal.in 375

6> release channel dev1;

7> }

Does Oracle write to data files in begin/hot backup mode? (for DBA ) Oracle will stop updating file headers, but will continue to write data to the database

files even if a tablespace is in backup mode.

In backup mode, Oracle will write out complete changed blocks to the redo log files.

Normally only deltas (changes) are logged to the redo logs. This is done to enable

reconstruction of a block if only half of it was backed up (split blocks). Because of

this, one should notice increased log activity and archiving during on-line backups.

What is the Maximum allowed length of Record group Column?

Record group column names cannot exceed 30 characters.

Which parameter can be used to set read level consistency across multiple

queries? Read only

What are the different types of Record Groups? Query Record Groups

NonQuery Record Groups

State Record Groups

From which designation is it preferred to send the output to the printed? Previewer

What are difference between post database commit and post-form commit? Post-form commit fires once during the post and commit transactions process, after the

database commit occurs. The post-form-commit trigger fires after inserts, updates and

deletes have been posted to the database but before the transactions have been

finalized in the issuing the command. The post-database-commit trigger fires after

oracle forms issues the commit to finalized transactions.

What are the different display styles of list items? Pop_listText_listCombo box

Which of the above methods is the faster method?

performing the calculation in the query is faster.

© Copyright : IT Engg Portal – www.itportal.in 376

With which function of summary item is the compute at options required? percentage of total functions.

What are parameters? Parameters provide a simple mechanism for defining and setting the valuesof inputs

that are required by a form at startup. Form parameters are variables of type

char,number,date that you define at design time.

What are the three types of user exits available ? Oracle Precompiler exits, Oracle call interface, NonOracle user exits.

How many windows in a form can have console? Only one window in a form can display the console, and you cannot change the

console assignment at runtime.

What is an administrative (privileged) user? (for DBA ) Oracle DBAs and operators typically use administrative accounts to manage the

database and database instance. An administrative account is a user that is granted

SYSOPER or SYSDBA privileges. SYSDBA and SYSOPER allow access to a

database instance even if it is not running. Control of these privileges is managed

outside of the database via password files and special operating system groups. This

password file is created with the orapwd utility.

What are the two repeating frame always associated with matrix object? One down repeating frame below one across repeating frame.

What are the master-detail triggers? On-Check_delete_masterOn_clear_detailsOn_populate_details

How does one connect to an administrative user? (for DBA ) If an administrative user belongs to the "dba" group on Unix, or the "ORA_DBA"

(ORA_sid_DBA) group on NT, he/she can connect like this:

connect / as sysdba

No password is required. This is equivalent to the desupported "connect internal"

method.

A password is required for "non-secure" administrative access. These passwords are

stored in password files. Remote connections via Net8 are classified as non-secure.

© Copyright : IT Engg Portal – www.itportal.in 377

Look at this example:

connect sys/password as sysdba

How does one create a password file? (for DBA ) The Oracle Password File ($ORACLE_HOME/dbs/orapw or orapwSID) stores

passwords for users with administrative privileges. One needs to create a password

files before remote administrators (like OEM) will be allowed to connect.

Follow this procedure to create a new password file:

. Log in as the Oracle software owner

. Runcommand: orapwd file=$ORACLE_HOME/dbs/orapw$ORACLE_SID

password=mypasswd

. Shutdown the database (SQLPLUS> SHUTDOWN IMMEDIATE)

. Edit the INIT.ORA file and ensure REMOTE_LOGIN_PASSWORDFILE=exclusive

is set.

. Startup the database (SQLPLUS> STARTUP)

NOTE: The orapwd utility presents a security risk in that it receives a password from

the command line. This password is visible in the process table of many systems.

Administrators needs to be aware of this!

Is it possible to modify an external query in a report which contains it? No.

Does a grouping done for objects in the layout editor affect the grouping done in

the data model editor? No.

How does one add users to a password file? (for DBA ) One can select from the SYS.V_$PWFILE_USERS view to see which users are listed

in the password file. New users can be added to the password file by granting them

SYSDBA or SYSOPER privileges, or by using the orapwd utility. GRANT SYSDBA

TO scott;

If a break order is set on a column would it affect columns which are under the

column? No

Why are OPS$ accounts a security risk in a client/server environment? (for DBA) If you allow people to log in with OPS$ accounts from Windows Workstations, you

© Copyright : IT Engg Portal – www.itportal.in 378

cannot be sure who they really are. With terminals, you can rely on operating system

passwords, with Windows, you cannot.

If you set REMOTE_OS_AUTHENT=TRUE in your init.ora file, Oracle assumes that

the remote OS has authenticated the user. If REMOTE_OS_AUTHENT is set to

FALSE (recommended), remote users will be unable to connect without a password.

IDENTIFIED EXTERNALLY will only be in effect from the local host. Also, if you

are using "OPS$" as your prefix, you will be able to log on locally with or without a

password, regardless of whether you have identified your ID with a password or

defined it to be IDENTIFIED EXTERNALLY.

Do user parameters appear in the data modal editor in 2.5? No

Can you pass data parameters to forms? No

Is it possible to link two groups inside a cross products after the cross products

group has been created? no

What are the different modals of windows? Modalless windows

Modal windows

What are modal windows? Modal windows are usually used as dialogs, and have restricted functionality

compared to modelless windows. On some platforms for example operators cannot

resize, scroll or iconify a modal window.

What are the different default triggers created when Master Deletes Property is

set to Non-isolated?

Master Deletes Property Resulting Triggers

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

Non-Isolated(the default) On-Check-Delete-Master

On-Clear-Details

On-Populate-Details

© Copyright : IT Engg Portal – www.itportal.in 379

What are the different default triggers created when Master Deletes Property is

set to isolated?

Master Deletes Property Resulting Triggers

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

Isolated On-Clear-Details

On-Populate-Details

What are the different default triggers created when Master Deletes Property is

set to Cascade? Master Deletes Property Resulting Triggers

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

Cascading On-Clear-Details

On-Populate-Details

Pre-delete

What is the diff. bet. setting up of parameters in reports 2.0 reports2.5? LOVs can be attached to parameters in the reports 2.5 parameter form.

What are the difference between lov & list item? Lov is a property where as list item is an item. A list item can have only one column,

lov can have one or more columns.

What is the advantage of the library?

Libraries provide a convenient means of storing client-side program units and sharing

them among multiple applications. Once you create a library, you can attach it to any

other form, menu, or library modules. When you can call library program units from

triggers menu items commands and user named routine, you write in the modules to

which you have attach the library. When a library attaches another library, program

units in the first library can reference program units in the attached library. Library

support dynamic loading-that is library program units are loaded into an application

only when needed. This can significantly reduce the run-time memory requirements of

applications.

What is lexical reference? How can it be created? Lexical reference is place_holder for text that can be embedded in a sql statements. A

lexical reference can be created using & before the column or parameter name.

© Copyright : IT Engg Portal – www.itportal.in 380

What is system.coordination_operation? It represents the coordination causing event that occur on the master block in master-

detail relation.

What is synchronize?

It is a terminal screen with the internal state of the form. It updates the screen display

to reflect the information that oracle forms has in its internal representation of the

screen.

What use of command line parameter cmd file? It is a command line argument that allows you to specify a file that contain a set of

arguments for r20run.

What is a Text_io Package? It allows you to read and write information to a file in the file system.

What is forms_DDL? Issues dynamic Sql statements at run time, including server side pl/SQl and DDL

How is link tool operation different bet. reports 2 & 2.5? In Reports 2.0 the link tool has to be selected and then two fields to be linked are

selected and the link is automatically created. In 2.5 the first field is selected and the

link tool is then used to link the first field to the second field.

What are the different styles of activation of ole Objects? In place activationExternal activation

How do you reference a Parameter? In Pl/Sql, You can reference and set the values of form parameters using bind

variables syntax. Ex. PARAMETER name = '' or :block.item = PARAMETER

Parameter name

What is the difference between object embedding & linking in Oracle forms? In Oracle forms, Embedded objects become part of the form module, and linked

objects are references from a form module to a linked source file.

Name of the functions used to get/set canvas properties? Get_view_property, Set_view_property

© Copyright : IT Engg Portal – www.itportal.in 381

What are the built-ins that are used for setting the LOV properties at runtime? get_lov_property

set_lov_property

What are the built-ins used for processing rows? Get_group_row_count(function)

Get_group_selection_count(function)

Get_group_selection(function)

Reset_group_selection(procedure)

Set_group_selection(procedure)

Unset_group_selection(procedure)

What are built-ins used for Processing rows? GET_GROUP_ROW_COUNT(function)

GET_GROUP_SELECTION_COUNT(function)

GET_GROUP_SELECTION(function)

RESET_GROUP_SELECTION(procedure)

SET_GROUP_SELECTION(procedure)

UNSET_GROUP_SELECTION(procedure)

What are the built-in used for getting cell values? Get_group_char_cell(function)

Get_groupcell(function)

Get_group_number_cell(function)

What are the built-ins used for Getting cell values? GET_GROUP_CHAR_CELL (function)

GET_GROUPCELL(function)

GET_GROUP_NUMBET_CELL(function)

Atleast how many set of data must a data model have before a data model can be

base on it? Four

To execute row from being displayed that still use column in the row which

property can be used? Format trigger.

© Copyright : IT Engg Portal – www.itportal.in 382

What are different types of modules available in oracle form? Form module - a collection of objects and code routines Menu modules - a collection

of menus and menu item commands that together make up an application menu library

module - a collection of user named procedures, functions and packages that can be

called from other modules in the application

What is the remove on exit property?

For a modelless window, it determines whether oracle forms hides the window

automatically when the operators navigates to an item in the another window.

What is WHEN-Database-record trigger? Fires when oracle forms first marks a record as an insert or an update. The trigger fires

as soon as oracle forms determines through validation that the record should be

processed by the next post or commit as an insert or update. c generally occurs only

when the operators modifies the first item in the record, and after the operator attempts

to navigate out of the item.

What is a difference between pre-select and pre-query? Fires during the execute query and count query processing after oracle forms

constructs the select statement to be issued, but before the statement is actually issued.

The pre-query trigger fires just before oracle forms issues the select statement to the

database after the operator as define the example records by entering the query criteria

in enter query mode.Pre-query trigger fires before pre-select trigger.

What are built-ins associated with timers? find_timercreate_timerdelete_timer

What are the built-ins used for finding object ID functions? Find_group(function)

Find_column(function)

What are the built-ins used for finding Object ID function? FIND_GROUP(function)

FIND_COLUMN(function)

Any attempt to navigate programmatically to disabled form in a call_form stack

is allowed? False

© Copyright : IT Engg Portal – www.itportal.in 383

Use the Add_group_row procedure to add a row to a static record group 1. true

or false? False

What third party tools can be used with Oracle EBU/ RMAN? (for DBA)

The following Media Management Software Vendors have integrated their media

management software packages with Oracle Recovery Manager and Oracle7

Enterprise Backup Utility. The Media Management Vendors will provide first line

technical support for the integrated backup/recover solutions.

Veritas NetBackup

EMC Data Manager (EDM)

HP OMNIBack II

IBM's Tivoli Storage Manager - formerly ADSM

Legato Networker

ManageIT Backup and Recovery

Sterling Software's SAMS:Alexandria - formerly from Spectralogic

Sun Solstice Backup

Why and when should one tune? (for DBA) One of the biggest responsibilities of a DBA is to ensure that the Oracle database is

tuned properly. The Oracle RDBMS is highly tunable and allows the database to be

monitored and adjusted to increase its performance. One should do performance

tuning for the following reasons:

The speed of computing might be wasting valuable human time (users waiting for

response); Enable your system to keep-up with the speed business is conducted; and

Optimize hardware usage to save money (companies are spending millions on

hardware). Although this FAQ is not overly concerned with hardware issues, one

needs to remember than you cannot tune a Buick into a Ferrari.

How can a break order be created on a column in an existing group? What are

the various sub events a mouse double click event involves? By dragging the column outside the group.

What is the use of place holder column? What are the various sub events a mouse

double click event involves? A placeholder column is used to hold calculated values at a specified place rather than

allowing is to appear in the actual row where it has to appear.

© Copyright : IT Engg Portal – www.itportal.in 384

What is the use of hidden column? What are the various sub events a mouse

double click event involves? A hidden column is used to when a column has to embed into boilerplate text.

What database aspects should be monitored? (for DBA) One should implement a monitoring system to constantly monitor the following

aspects of a database. Writing custom scripts, implementing Oracle's Enterprise

Manager, or buying a third-party monitoring product can achieve this. If an alarm is

triggered, the system should automatically notify the DBA (e-mail, page, etc.) to take

appropriate action.

Infrastructure availability:

. Is the database up and responding to requests

. Are the listeners up and responding to requests

. Are the Oracle Names and LDAP Servers up and responding to requests

. Are the Web Listeners up and responding to requests

Things that can cause service outages:

. Is the archive log destination filling up?

. Objects getting close to their max extents

. User and process limits reached

Things that can cause bad performance:

See question "What tuning indicators can one use?".

Where should the tuning effort be directed? (for DBA) Consider the following areas for tuning. The order in which steps are listed needs to be

maintained to prevent tuning side effects. For example, it is no good increasing the

buffer cache if you can reduce I/O by rewriting a SQL statement. Database Design (if

it's not too late):

Poor system performance usually results from a poor database design. One should

generally normalize to the 3NF. Selective denormalization can provide valuable

performance improvements. When designing, always keep the "data access path" in

mind. Also look at proper data partitioning, data replication, aggregation tables for

decision support systems, etc.

Application Tuning:

Experience showed that approximately 80% of all Oracle system performance

problems are resolved by coding optimal SQL. Also consider proper scheduling of

© Copyright : IT Engg Portal – www.itportal.in 385

batch tasks after peak working hours.

Memory Tuning:

Properly size your database buffers (shared pool, buffer cache, log buffer, etc) by

looking at your buffer hit ratios. Pin large objects into memory to prevent frequent

reloads.

Disk I/O Tuning:

Database files needs to be properly sized and placed to provide maximum disk

subsystem throughput. Also look for frequent disk sorts, full table scans, missing

indexes, row chaining, data fragmentation, etc

Eliminate Database Contention:

Study database locks, latches and wait events carefully and eliminate where possible.

Tune the Operating System:

Monitor and tune operating system CPU, I/O and memory utilization. For more

information, read the related Oracle FAQ dealing with your specific operating system.

What are the various sub events a mouse double click event involves? What are

the various sub events a mouse double click event involves? Double clicking the mouse consists of the mouse down, mouse up, mouse click, mouse

down & mouse up events.

What are the default parameter that appear at run time in the parameter screen?

What are the various sub events a mouse double click event involves? Destype and Desname.

What are the built-ins used for Creating and deleting groups? CREATE-GROUP (function)

CREATE_GROUP_FROM_QUERY(function)

DELETE_GROUP(procedure)

What are different types of canvas views? Content canvas views

Stacked canvas views

Horizontal toolbar

vertical toolbar.

What are the different types of Delete details we can establish in Master-Details? Cascade

© Copyright : IT Engg Portal – www.itportal.in 386

Isolate

Non-isolate

What is relation between the window and canvas views? Canvas views are the back ground objects on which you place the interface items

(Text items), check boxes, radio groups etc.,) and boilerplate objects (boxes, lines,

images etc.,) that operators interact with us they run your form . Each canvas views

displayed in a window.

What is a User_exit? Calls the user exit named in the user_exit_string. Invokes a 3Gl program by name

which has been properly linked into your current oracle forms executable.

How is it possible to select generate a select set for the query in the query

property sheet? By using the tables/columns button and then specifying the table and the column

names.

How can values be passed bet. precompiler exits & Oracle call interface? By using the statement EXECIAFGET & EXECIAFPUT.

How can a square be drawn in the layout editor of the report writer? By using the rectangle tool while pressing the (Constraint) key.

How can a text file be attached to a report while creating in the report writer? By using the link file property in the layout boiler plate property sheet.

How can I message to passed to the user from reports? By using SRW.MESSAGE function.

Does one need to drop/ truncate objects before importing? (for DBA) Before one import rows into already populated tables, one needs to truncate or drop

these tables to get rid of the old data. If not, the new data will be appended to the

existing tables. One must always DROP existing Sequences before re-importing. If the

sequences are not dropped, they will generate numbers inconsistent with the rest of the

database. Note: It is also advisable to drop indexes before importing to speed up the

import process. Indexes can easily be recreated after the data was successfully

imported.

© Copyright : IT Engg Portal – www.itportal.in 387

How can a button be used in a report to give a drill down facility? By setting the action associated with button to Execute pl/sql option and using the

SRW.Run_report function.

Can one import/export between different versions of Oracle? (for DBA) Different versions of the import utility is upwards compatible. This means that one can

take an export file created from an old export version, and import it using a later

version of the import utility. This is quite an effective way of upgrading a database

from one release of Oracle to the next.

Oracle also ships some previous catexpX.sql scripts that can be executed as user SYS

enabling older imp/exp versions to work (for backwards compatibility). For example,

one can run $ORACLE_HOME/rdbms/admin/catexp7.sql on an Oracle 8 database to

allow the Oracle 7.3 exp/imp utilities to run against an Oracle 8 database.

What are different types of images? Boiler plate imagesImage Items

Can one export to multiple files?/ Can one beat the Unix 2 Gig limit? (for DBA) From Oracle8i, the export utility supports multiple output files. This feature enables

large exports to be divided into files whose sizes will not exceed any operating system

limits (FILESIZE= parameter). When importing from multi-file export you must

provide the same filenames in the same sequence in the FILE= parameter. Look at this

example:

exp SCOTT/TIGER FILE=D:\F1.dmp,E:\F2.dmp FILESIZE=10m LOG=scott.log

Use the following technique if you use an Oracle version prior to 8i:

Create a compressed export on the fly. Depending on the type of data, you probably

can export up to 10 gigabytes to a single file. This example uses gzip. It offers the best

compression I know of, but you can also substitute it with zip, compress or whatever.

# create a named pipe

mknod exp.pipe p

# read the pipe - output to zip file in the background

gzip < exp.pipe > scott.exp.gz &

# feed the pipe

exp userid=scott/tiger file=exp.pipe ...

What is bind reference and how can it be created? Bind reference are used to replace the single value in sql, pl/sql statements a bind

reference can be created using a (:) before a column or a parameter name.

© Copyright : IT Engg Portal – www.itportal.in 388

How can one improve Import/ Export performance? (for DBA) EXPORT:

. Set the BUFFER parameter to a high value (e.g. 2M)

. Set the RECORDLENGTH parameter to a high value (e.g. 64K)

. Stop unnecessary applications to free-up resources for your job.

. If you run multiple export sessions, ensure they write to different physical disks.

. DO NOT export to an NFS mounted filesystem. It will take forever.

IMPORT:

. Create an indexfile so that you can create indexes AFTER you have imported data.

Do this by setting INDEXFILE to a filename and then import. No data will be

imported but a file containing index definitions will be created. You must edit this file

afterwards and supply the passwords for the schemas on all CONNECT statements.

. Place the file to be imported on a separate physical disk from the oracle data files

. Increase DB_CACHE_SIZE (DB_BLOCK_BUFFERS prior to 9i) considerably in

the init$SID.ora file

. Set the LOG_BUFFER to a big value and restart oracle.

. Stop redo log archiving if it is running (ALTER DATABASE NOARCHIVELOG;)

. Create a BIG tablespace with a BIG rollback segment inside. Set all other rollback

segments offline (except the SYSTEM rollback segment of course). The rollback

segment must be as big as your biggest table (I think?)

. Use COMMIT=N in the import parameter file if you can afford it

. Use ANALYZE=N in the import parameter file to avoid time consuming ANALYZE

statements

. Remember to run the indexfile previously created

Give the sequence of execution of the various report triggers? Before form , After form , Before report, Between page, After report.

What are the common Import/ Export problems? (for DBA ) ORA-00001: Unique constraint (...) violated - You are importing duplicate rows. Use

IGNORE=NO to skip tables that already exist (imp will give an error if the object is

re-created).

ORA-01555: Snapshot too old - Ask your users to STOP working while you are

exporting or use parameter CONSISTENT=NO

ORA-01562: Failed to extend rollback segment - Create bigger rollback segments or

© Copyright : IT Engg Portal – www.itportal.in 389

set parameter COMMIT=Y while importing

IMP-00015: Statement failed ... object already exists... - Use the IGNORE=Y import

parameter to ignore these errors, but be careful as you might end up with duplicate

rows.

Why is it preferable to create a fewer no. of queries in the data model? Because for each query, report has to open a separate cursor and has to rebind, execute

and fetch data.

Where is the external query executed at the client or the server?

At the server.

Where is a procedure return in an external pl/sql library executed at the client or

at the server? At the client.

What is coordination Event? Any event that makes a different record in the master block the current record is a

coordination causing event.

What is the difference between OLE Server & Ole Container? An Ole server application creates ole Objects that are embedded or linked in ole

Containers ex. Ole servers are ms_word & ms_excel. OLE containers provide a place

to store, display and manipulate objects that are created by ole server applications. Ex.

oracle forms is an example of an ole Container.

What is an object group?

An object group is a container for a group of objects; you define an object group when

you want to package related objects, so that you copy or reference them in other

modules.

What is an LOV? An LOV is a scrollable popup window that provides the operator with either a single

or multi column selection list.

At what point of report execution is the before Report trigger fired? After the query is executed but before the report is executed and the records are

displayed.

© Copyright : IT Engg Portal – www.itportal.in 390

What are the built -ins used for Modifying a groups structure? ADD-GROUP_COLUMN (function)

ADD_GROUP_ROW (procedure)

DELETE_GROUP_ROW(procedure)

What is an user exit used for? A way in which to pass control (and possibly arguments ) form Oracle report to

another Oracle products of 3 GL and then return control ( and ) back to Oracle reports.

What is the User-Named Editor? A user named editor has the same text editing functionality as the default editor, but,

because it is a named object, you can specify editor attributes such as windows display

size, position, and title.

My database was terminated while in BACKUP MODE, do I need to recover?

(for DBA) If a database was terminated while one of its tablespaces was in BACKUP MODE

(ALTER TABLESPACE xyz BEGIN BACKUP;), it will tell you that media recovery

is required when you try to restart the database. The DBA is then required to recover

the database and apply all archived logs to the database. However, from Oracle7.2,

you can simply take the individual datafiles out of backup mode and restart the

database.

ALTER DATABASE DATAFILE '/path/filename' END BACKUP;

One can select from V$BACKUP to see which datafiles are in backup mode. This

normally saves a significant amount of database down time.

Thiru Vadivelu contributed the following:

From Oracle9i onwards, the following command can be used to take all of the

datafiles out of hot backup mode:

ALTER DATABASE END BACKUP;

The above commands need to be issued when the database is mounted.

What is a Static Record Group? A static record group is not associated with a query, rather, you define its structure and

row values at design time, and they remain fixed at runtime.

What is a record group? A record group is an internal Oracle Forms that structure that has a column/row

© Copyright : IT Engg Portal – www.itportal.in 391

framework similar to a database table. However, unlike database tables, record groups

are separate objects that belong to the form module which they are defined.

My database is down and I cannot restore. What now? (for DBA ) Recovery without any backup is normally not supported, however, Oracle Consulting

can sometimes extract data from an offline database using a utility called DUL (Disk

UnLoad). This utility reads data in the data files and unloads it into SQL*Loader or

export dump files. DUL does not care about rollback segments, corrupted blocks, etc,

and can thus not guarantee that the data is not logically corrupt. It is intended as an

absolute last resort and will most likely cost your company a lot of money!!!

I've lost my REDOLOG files, how can I get my DB back? (for DBA) The following INIT.ORA parameter may be required if your current redo logs are

corrupted or blown away. Caution is advised when enabling this parameter as you

might end-up losing your entire database. Please contact Oracle Support before using

it. _allow_resetlogs_corruption = true

What is a property clause? A property clause is a named object that contains a list of properties and their settings.

Once you create a property clause you can base other object on it. An object based on

a property can inherit the setting of any property in the clause that makes sense for that

object.

What is a physical page ? & What is a logical page ? A physical page is a size of a page. That is output by the printer. The logical page is

the size of one page of the actual report as seen in the Previewer.

I've lost some Rollback Segments, how can I get my DB back? (for DBA) Re-start your database with the following INIT.ORA parameter if one of your rollback

segments is corrupted. You can then drop the corrupted rollback segments and create it

from scratch.

Caution is advised when enabling this parameter, as uncommitted transactions will be

marked as committed. One can very well end up with lost or inconsistent data!!!

Please contact Oracle Support before using it. _Corrupted_rollback_segments =

(rbs01, rbs01, rbs03, rbs04)

What are the differences between EBU and RMAN? (for DBA) Enterprise Backup Utility (EBU) is a functionally rich, high performance interface for

© Copyright : IT Engg Portal – www.itportal.in 392

backing up Oracle7 databases. It is sometimes referred to as OEBU for Oracle

Enterprise Backup Utility. The Oracle Recovery Manager (RMAN) utility that ships

with Oracle8 and above is similar to Oracle7's EBU utility. However, there is no direct

upgrade path from EBU to RMAN.

How does one create a RMAN recovery catalog? (for DBA) Start by creating a database schema (usually called rman). Assign an appropriate

tablespace to it and grant it the recovery_catalog_owner role. Look at this example:

sqlplus sys

SQL>create user rman identified by rman;

SQL> alter user rman default tablespace tools temporary tablespace temp;

SQL> alter user rman quota unlimited on tools;

SQL> grant connect, resource, recovery_catalog_owner to rman;

SQL> exit;

Next, log in to rman and create the catalog schema. Prior to Oracle 8i this was done by

running the catrman.sql script. rman catalog rman/rman

RMAN>create catalog tablespace tools;

RMAN> exit;

You can now continue by registering your databases in the catalog. Look at this

example:

rman catalog rman/rman target backdba/backdba

RMAN> register database;

How can a group in a cross products be visually distinguished from a group that

does not form a cross product? A group that forms part of a cross product will have a thicker border.

What is the frame & repeating frame? A frame is a holder for a group of fields. A repeating frame is used to display a set of

records when the no. of records that are to displayed is not known before.

What is a combo box? A combo box style list item combines the features found in list and text item. Unlike

the pop list or the text list style list items, the combo box style list item will both

display fixed values and accept one operator entered value.

What are three panes that appear in the run time pl/sql interpreter?

1. Source pane.

© Copyright : IT Engg Portal – www.itportal.in 393

2. interpreter pane.

3. Navigator pane.

What are the two panes that Appear in the design time pl/sql interpreter? 1. Source pane.

2. Interpreter pane

What are the two ways by which data can be generated for a parameters list of

values? 1. Using static values.

2. Writing select statement.

What are the various methods of performing a calculation in a report ? 1. Perform the calculation in the SQL statements itself.

2. Use a calculated / summary column in the data model.

What are the default extensions of the files created by menu module? .mmb,

.mmx

What are the default extensions of the files created by forms modules? .fmb - form module binary

.fmx - form module executable

To display the page no. for each page on a report what would be the source &

logical page no. or & of physical page no.? & physical page no.

It is possible to use raw devices as data files and what is the advantages over file.

system files ?

Yes. The advantages over file system files. I/O will be improved because Oracle is

bye-passing the kernnel which writing into disk. Disk Corruption will be very less.

What are disadvantages of having raw devices ? We should depend on export/import utility for backup/recovery (fully reliable) The tar

command cannot be used for physical file backup, instead we can use dd command

which is less flexible and has limited recoveries.

© Copyright : IT Engg Portal – www.itportal.in 394

What is the significance of having storage clause ? We can plan the storage for a table as how much initial extents are required, how

much can be extended next, how much % should leave free for managing row

updations etc.,

What is the use of INCTYPE option in EXP command ? Type export should be performed COMPLETE,CUMULATIVE,INCREMENTAL.

List the sequence of events when a large transaction that exceeds beyond its optimal

value when an entry wraps and causes the rollback segment toexpand into anotion

Completes. e. will be written.

What is the use of FILE option in IMP command ? The name of the file from which import should be performed.

What is a Shared SQL pool? The data dictionary cache is stored in an area in SGA called the Shared SQL Pool.

This will allow sharing of parsed SQL statements among concurrent users.

What is hot backup and how it can be taken? Taking backup of archive log files when database is open. For this the ARCHIVELOG

mode should be enabled. The following files need to be backed up. All data files. All

Archive log, redo log files. All control files.

List the Optional Flexible Architecture (OFA) of Oracle database? or How can

we organize the tablespaces in Oracle database to have maximum performance ? SYSTEM - Data dictionary tables.

DATA - Standard operational tables.

DATA2- Static tables used for standard operations

INDEXES - Indexes for Standard operational tables.

INDEXES1 - Indexes of static tables used for standard operations.

TOOLS - Tools table.

TOOLS1 - Indexes for tools table.

RBS - Standard Operations Rollback Segments,

RBS1,RBS2 - Additional/Special Rollback segments.

TEMP - Temporary purpose tablespace

TEMP_USER - Temporary tablespace for users.

USERS - User tablespace.

© Copyright : IT Engg Portal – www.itportal.in 395

How to implement the multiple control files for an existing database ? Shutdown the database Copy one of the existing control file to new location Edit

Config ora file by adding new control file. name Restart the database.

What is advantage of having disk shadowing/ Mirroring ? Shadow set of disks save as a backup in the event of disk failure. In most Operating

System if any disk failure occurs it automatically switchover to place of failed disk.

Improved performance because most OS support volume shadowing can direct file I/O

request to use the shadow set of files instead of the main set of files. This reduces I/O

load on the main set of disks.

How will you force database to use particular rollback segment ? SET TRANSACTION USE ROLLBACK SEGMENT rbs_name.

Why query fails sometimes ? Rollback segment dynamically extent to handle larger transactions entry loads. A

single transaction may wipeout all available free space in the Rollback Segment

Tablespace. This prevents other user using Rollback segments.

What is the use of RECORD LENGTH option in EXP command ? Record length in bytes.

How will you monitor rollback segment status ? Querying the DBA_ROLLBACK_SEGS view

IN USE - Rollback Segment is on-line.

AVAILABLE - Rollback Segment available but not on-line.

OFF-LINE - Rollback Segment off-line

INVALID - Rollback Segment Dropped.

NEEDS RECOVERY - Contains data but need recovery or corupted.

PARTLY AVAILABLE - Contains data from an unresolved transaction involving a

distributed database.

What is meant by Redo Log file mirroring ? How it can be achieved? Process of having a copy of redo log files is called mirroring. This can be achieved by

creating group of log files together, so that LGWR will automatically writes them to

all the members of the current on-line redo log group. If any one group fails then

database automatically switch over to next group. It degrades performance.

© Copyright : IT Engg Portal – www.itportal.in 396

Which parameter in Storage clause will reduce no. of rows per block? PCTFREE parameter

Row size also reduces no of rows per block.

What is meant by recursive hints ? Number of times processes repeatedly query the dictionary table is called recursive

hints. It is due to the data dictionary cache is too small. By increasing the

SHARED_POOL_SIZE parameter we can optimize the size of Data Dictionary Cache.

What is the use of PARFILE option in EXP command ? Name of the parameter file to be passed for export.

What is the difference between locks, latches, enqueues and semaphores? (for

DBA) A latch is an internal Oracle mechanism used to protect data structures in the SGA

from simultaneous access. Atomic hardware instructions like TEST-AND-SET is used

to implement latches. Latches are more restrictive than locks in that they are always

exclusive. Latches are never queued, but will spin or sleep until they obtain a resource,

or time out.

Enqueues and locks are different names for the same thing. Both support queuing and

concurrency. They are queued and serviced in a first-in-first-out (FIFO) order.

Semaphores are an operating system facility used to control waiting. Semaphores are

controlled by the following Unix parameters: semmni, semmns and semmsl. Typical

settings are:

semmns = sum of the "processes" parameter for each instance

(see init<instance>.ora for each instance)

semmni = number of instances running simultaneously;

semmsl = semmns

What is a logical backup? Logical backup involves reading a set of database records and writing them into a file.

Export utility is used for taking backup and Import utility is used to recover from

backup.

Where can one get a list of all hidden Oracle parameters? (for DBA) Oracle initialization or INIT.ORA parameters with an underscore in front are hidden

or unsupported parameters. One can get a list of all hidden parameters by executing

this query:

© Copyright : IT Engg Portal – www.itportal.in 397

select *

from SYS.X$KSPPI

where substr(KSPPINM,1,1) = '_';

The following query displays parameter names with their current value:

select a.ksppinm "Parameter", b.ksppstvl "Session Value", c.ksppstvl "Instance Value"

from x$ksppi a, x$ksppcv b, x$ksppsv c

where a.indx = b.indx and a.indx = c.indx

and substr(ksppinm,1,1)='_'

order by a.ksppinm;

Remember: Thou shall not play with undocumented parameters!

What is a database EVENT and how does one set it? (for DBA) Oracle trace events are useful for debugging the Oracle database server. The following

two examples are simply to demonstrate syntax. Refer to later notes on this page for an

explanation of what these particular events do.

Either adding them to the INIT.ORA parameter file can activate events. E.g.

event='1401 trace name errorstack, level 12'

... or, by issuing an ALTER SESSION SET EVENTS command: E.g.

alter session set events '10046 trace name context forever, level 4';

The alter session method only affects the user's current session, whereas changes to the

INIT.ORA file will affect all sessions once the database has been restarted.

What is a Rollback segment entry ? It is the set of before image data blocks that contain rows that are modified by a

transaction. Each Rollback Segment entry must be completed within one rollback

segment. A single rollback segment can have multiple rollback segment entries.

What database events can be set? (for DBA) The following events are frequently used by DBAs and Oracle Support to diagnose

problems:

" 10046 trace name context forever, level 4 Trace SQL statements and show bind

variables in trace output.

" 10046 trace name context forever, level 8 This shows wait events in the SQL trace

files

" 10046 trace name context forever, level 12 This shows both bind variable names and

wait events in the SQL trace files

" 1401 trace name errorstack, level 12 1401 trace name errorstack, level 4 1401 trace

© Copyright : IT Engg Portal – www.itportal.in 398

name processstate Dumps out trace information if an ORA-1401 "inserted value too

large for column" error occurs. The 1401 can be replaced by any other Oracle Server

error code that you want to trace.

" 60 trace name errorstack level 10 Show where in the code Oracle gets a deadlock

(ORA-60), and may help to diagnose the problem.

The following lists of events are examples only. They might be version specific, so

please call Oracle before using them:

" 10210 trace name context forever, level 10 10211 trace name context forever, level

10 10231 trace name context forever, level 10 These events prevent database block

corruptions

" 10049 trace name context forever, level 2 Memory protect cursor

" 10210 trace name context forever, level 2 Data block check

" 10211 trace name context forever, level 2 Index block check

" 10235 trace name context forever, level 1 Memory heap check

" 10262 trace name context forever, level 300 Allow 300 bytes memory leak for

connections

Note: You can use the Unix oerr command to get the description of an event. On Unix,

you can type "oerr ora 10053" from the command prompt to get event details.

How can one dump internal database structures? (for DBA) The following (mostly undocumented) commands can be used to obtain information

about internal database structures.

o Dump control file contents

alter session set events 'immediate trace name CONTROLF level 10'

/

o Dump file headers

alter session set events 'immediate trace name FILE_HDRS level 10'

/

o Dump redo log headers

alter session set events 'immediate trace name REDOHDR level 10'

/

o Dump the system state

NOTE: Take 3 successive SYSTEMSTATE dumps, with 10-minute intervals alter

session set events 'immediate trace name SYSTEMSTATE level 10'

/

o Dump the process state

alter session set events 'immediate trace name PROCESSSTATE level 10'

© Copyright : IT Engg Portal – www.itportal.in 399

/

o Dump Library Cache details

alter session set events 'immediate trace name library cache level 10'

/

o Dump optimizer statistics whenever a SQL statement is parsed (hint: change

statement or flush pool) alter session set events '10053 trace name context forever,

level 1'

/

o Dump a database block (File/ Block must be converted to DBA address) Convert file

and block number to a DBA (database block address).

Eg: variable x varchar2;

exec :x := dbms_utility.make_data_block_address(1,12);

print x

alter session set events 'immediate trace name blockdump level 50360894'

/

What are the different kind of export backups? Full back - Complete database

Incremental - Only affected tables from last incremental date/full backup date.

Cumulative backup - Only affected table from the last cumulative date/full backup

date.

How free extents are managed in Ver 6.0 and Ver 7.0 ? Free extents cannot be merged together in Ver 6.0.

Free extents are periodically coalesces with the neighboring free extent in Ver 7.0

What is the use of RECORD option in EXP command?

For Incremental exports, the flag indirects whether a record will be stores data

dictionary tables recording the export.

What is the use of ROWS option in EXP command ?

Flag to indicate whether table rows should be exported. If 'N' only DDL statements for

the database objects will be created.

What is the use of COMPRESS option in EXP command ? Flag to indicate whether export should compress fragmented segments into single

extents.

© Copyright : IT Engg Portal – www.itportal.in 400

How will you swap objects into a different table space for an existing database ? Export the user

Perform import using the command imp system/manager file=export.dmp

indexfile=newrite.sql.

This will create all definitions into newfile.sql. Drop necessary objects.

Run the script newfile.sql after altering the tablespaces.

Import from the backup for the necessary objects.

How does Space allocation table place within a block ? Each block contains entries as follows

Fixed block header

Variable block header

Row Header,row date (multiple rows may exists)

PCTEREE (% of free space for row updation in future)

What are the factors causing the reparsing of SQL statements in SGA? Due to insufficient Shared SQL pool size. Monitor the ratio of the reloads takes place

while executing SQL statements. If the ratio is greater than 1 then increase the

SHARED_POOL_SIZE. LOGICAL & PHYSICAL ARCHITECTURE OF

DATABASE.

What is dictionary cache ? Dictionary cache is information about the databse objects stored in a data dictionary

table.

What is a Control file ? Database overall physical architecture is maintained in a file called control file. It will

be used to maintain internal consistency and guide recovery operations. Multiple

copies of control files are advisable.

What is Database Buffers ? Database buffers are cache in the SGA used to hold the data blocks that are read from

the data segments in the database such as tables, indexes and clusters

DB_BLOCK_BUFFERS parameter in INIT.ORA decides the size.

How will you create multiple rollback segments in a database ? Create a database which implicitly creates a SYSTEM Rollback Segment in a

SYSTEM tablespace. Create a Second Rollback Segment name R0 in the SYSTEM

© Copyright : IT Engg Portal – www.itportal.in 401

tablespace. Make new rollback segment available (After shutdown, modify init.ora file

and Start database) Create other tablespaces (RBS) for rollback segments. Deactivate

Rollback Segment R0 and activate the newly created rollback segments.

What is cold backup? What are the elements of it? Cold backup is taking backup of all physical files after normal shutdown of database.

We need to take.

- All Data files.

- All Control files.

- All on-line redo log files.

- The init.ora file (Optional)

What is meant by redo log buffer ? Changes made to entries are written to the on-line redo log files. So that they can be

used in roll forward operations during database recoveries. Before writing them into

the redo log files, they will first brought to redo log buffers in SGA and LGWR will

write into files frequently. LOG_BUFFER parameter will decide the size.

How will you estimate the space required by a non-clustered tables? Calculate the total header size

Calculate the available dataspace per data block

Calculate the combined column lengths of the average row

Calculate the total average row size.

Calculate the average number rows that can fit in a block

Calculate the number of blocks and bytes required for the table.

After arriving the calculation, add 10 % additional space to calculate the initial extent

size for a working table.

How will you monitor the space allocation ? By querying DBA_SEGMENT table/view.

What is meant by free extent ? A free extent is a collection of continuous free blocks in tablespace. When a segment

is dropped its extents are reallocated and are marked as free.

What is the use of IGNORE option in IMP command ? A flag to indicate whether the import should ignore errors encounter when issuing

CREATE commands.

© Copyright : IT Engg Portal – www.itportal.in 402

What is the use of ANALYSE ( Ver 7) option in EXP command ? A flag to indicate whether statistical information about the exported objects should be

written to export dump file.

What is the use of ROWS option in IMP command ? A flag to indicate whether rows should be imported. If this is set to 'N' then only DDL

for database objects will be executed.

What is the use of INDEXES option in EXP command ? A flag to indicate whether indexes on tables will be exported.

What is the use of INDEXES option in IMP command ? A flag to indicate whether import should import index on tables or not.

What is the use of GRANT option in EXP command? A flag to indicate whether grants on databse objects will be exported or not. Value is

'Y' or 'N'.

What is the use of GRANT option in IMP command ? A flag to indicate whether grants on database objects will be imported.

What is the use of FULL option in EXP command ? A flag to indicate whether full databse export should be performed.

What is the use of SHOW option in IMP command ? A flag to indicate whether file content should be displayed or not.

What is the use of CONSTRAINTS option in EXP command ? A flag to indicate whether constraints on table need to be exported.

What is the use of CONSISTENT (Ver 7) option in EXP command ? A flag to indicate whether a read consistent version of all the exported objects should

be maintained.

What are the different methods of backing up oracle database ? - Logical Backups

- Cold Backups

- Hot Backups (Archive log)

© Copyright : IT Engg Portal – www.itportal.in 403

What is the difference between ON-VALIDATE-FIELD trigger and a POST-

CHANGE trigger ? When you changes the Existing value to null, the On-validate field trigger will fire

post change trigger will not fire. At the time of execute-query post-change trigger will

fire, on-validate field trigger will not fire.

When is PRE-QUERY trigger executed ? When Execute-query or count-query Package procedures are invoked.

How do you trap the error in forms 3.0 ?

using On-Message or On-Error triggers.

How many pages you can in a single form ? Unlimited

While specifying master/detail relationship between two blocks specifying the

join condition is a must ?

True or False. ? True

EXIT_FORM is a restricted package procedure ?

a. True b. False True

What is the usage of an ON-INSERT,ON-DELETE and ON-UPDATE

TRIGGERS ? These triggers are executes when inserting, deleting and updating operations are

performed and can be used to change the default function of insert, delete or update

respectively. For Eg, instead of inserting a row in a table an existing row can be

updated in the same table.

What are the types of Pop-up window ? the pop-up field editor

pop-up list of values

pop-up pages.

Alert :

© Copyright : IT Engg Portal – www.itportal.in 404

What is an SQL *FORMS ? SQL *forms is 4GL tool for developing and executing; Oracle based interactive

application.

How do you control the constraints in forms ? Select the use constraint property is ON Block definition screen.

BLOCK

What is the difference between restricted and unrestricted package procedure ? Restricted package procedure that affects the basic functions of SQL * Forms. It

cannot used in all triggers except key triggers. Unrestricted package procedure that

does not interfere with the basic functions of SQL * Forms it can be used in any

triggers.

A query fetched 10 records How many times does a PRE-QUERY Trigger and

POST-QUERY Trigger will get executed ?

PRE-QUERY fires once.

POST-QUERY fires 10 times.

Give the sequence in which triggers fired during insert operations, when the

following 3 triggers are defined at the same block level ? a. ON-INSERT b. POST-INSERT c. PRE-INSERT

State the order in which these triggers are executed ? POST-FIELD,ON-VALIDATE-FIELD,POST-CHANGE and KEY-NEXTFLD. KEY-

NEXTFLD,POST-CHANGE, ON-VALIDATE-FIELD, POST-FIELD. g.

What the PAUSE package procedure does ? Pause suspends processing until the operator presses a function key

What do you mean by a page ? Pages are collection of display information, such as constant text and graphics

What are the type of User Exits ? ORACLE Precompliers user exits

OCI (ORACLE Call Interface)

Non-ORACEL user exits.

Page :

© Copyright : IT Engg Portal – www.itportal.in 405

What is the difference between an ON-VALIDATE-FIELD trigger and a trigger

? On-validate-field trigger fires, when the field Validation status New or changed. Post-

field-trigger whenever the control leaving form the field, it will fire.

Can we use a restricted package procedure in ON-VALIDATE-FIELD Trigger ? No

Is a Key startup trigger fires as result of a operator pressing a key explicitly ? No

Can we use GO-BLOCK package in a pre-field trigger ? No

Can we create two blocks with the same name in form 3.0 ? No

What does an on-clear-block Trigger fire?

It fires just before SQL * forms the current block.

Name the two files that are created when you generate the form give the filex

extension ? INP (Source File)

FRM (Executable File)

What package procedure used for invoke sql *plus from sql *forms ? Host (E.g. Host (sqlplus))

What is the significance of PAGE 0 in forms 3.0 ? Hide the fields for internal calculation.

What are the different types of key triggers ? Function Key

Key-function

Key-others

Key-startup

What is the difference between a Function Key Trigger and Key Function

Trigger ?

© Copyright : IT Engg Portal – www.itportal.in 406

Function key triggers are associated with individual SQL*FORMS function keys You

can attach Key function triggers to 10 keys or key sequences that normally do not

perform any SQL * FORMS operations. These keys referred as key F0 through key

F9.

Committed block sometimes refer to a BASE TABLE ? False

Error_Code is a package proecdure ?

a. True b. false False

When is cost based optimization triggered? (for DBA)

It's important to have statistics on all tables for the CBO (Cost Based Optimizer) to

work correctly. If one table involved in a statement does not have statistics, Oracle has

to revert to rule-based optimization for that statement. So you really want for all tables

to have statistics right away; it won't help much to just have the larger tables analyzed.

Generally, the CBO can change the execution plan when you:

1. Change statistics of objects by doing an ANALYZE;

2. Change some initialization parameters (for example: hash_join_enabled,

sort_area_size, db_file_multiblock_read_count).

How can one optimize %XYZ% queries? (for DBA) It is possible to improve %XYZ% queries by forcing the optimizer to scan all the

entries from the index instead of the table. This can be done by specifying hints. If the

index is physically smaller than the table (which is usually the case) it will take less

time to scan the entire index than to scan the entire table.

What Enter package procedure does ? Enter Validate-data in the current validation unit.

Where can one find I/O statistics per table? (for DBA) The UTLESTAT report shows I/O per tablespace but one cannot see what tables in the

tablespace has the most I/O. The $ORACLE_HOME/rdbms/admin/catio.sql script

creates a sample_io procedure and table to gather the required information. After

executing the procedure, one can do a simple SELECT * FROM io_per_object; to

extract the required information. For more details, look at the header comments in the

$ORACLE_HOME/rdbms/admin/catio.sql script.

© Copyright : IT Engg Portal – www.itportal.in 407

My query was fine last week and now it is slow. Why? (for DBA) The likely cause of this is because the execution plan has changed. Generate a current

explain plan of the offending query and compare it to a previous one that was taken

when the query was performing well. Usually the previous plan is not available.

Some factors that can cause a plan to change are:

. Which tables are currently analyzed? Were they previously analyzed? (ie. Was the

query using RBO and now CBO?)

. Has OPTIMIZER_MODE been changed in INIT.ORA?

. Has the DEGREE of parallelism been defined/changed on any table?

. Have the tables been re-analyzed? Were the tables analyzed using estimate or

compute? If estimate, what percentage was used?

. Have the statistics changed?

. Has the INIT.ORA parameter DB_FILE_MULTIBLOCK_READ_COUNT been

changed?

. Has the INIT.ORA parameter SORT_AREA_SIZE been changed?

. Have any other INIT.ORA parameters been changed?

. What do you think the plan should be? Run the query with hints to see if this

produces the required performance.

Why is Oracle not using the damn index? (for DBA) This problem normally only arises when the query plan is being generated by the Cost

Based Optimizer. The usual cause is because the CBO calculates that executing a Full

Table Scan would be faster than accessing the table via the index.

Fundamental things that can be checked are:

. USER_TAB_COLUMNS.NUM_DISTINCT - This column defines the number of

distinct values the column holds.

. USER_TABLES.NUM_ROWS - If NUM_DISTINCT = NUM_ROWS then using an

index would be preferable to doing a FULL TABLE SCAN. As the NUM_DISTINCT

decreases, the cost of using an index increase thereby is making the index less

desirable.

. USER_INDEXES.CLUSTERING_FACTOR - This defines how ordered the rows

are in the index. If CLUSTERING_FACTOR approaches the number of blocks in the

table, the rows are ordered. If it approaches the number of rows in the table, the rows

are randomly ordered. In such a case, it is unlikely that index entries in the same leaf

block will point to rows in the same data blocks.

. Decrease the INIT.ORA parameter DB_FILE_MULTIBLOCK_READ_COUNT - A

higher value will make the cost of a FULL TABLE SCAN cheaper.

© Copyright : IT Engg Portal – www.itportal.in 408

. Remember that you MUST supply the leading column of an index, for the index to be

used (unless you use a FAST FULL SCAN or SKIP SCANNING).

. There are many other factors that affect the cost, but sometimes the above can help to

show why an index is not being used by the CBO. If from checking the above you still

feel that the query should be using an index, try specifying an index hint. Obtain an

explain plan of the query either using TKPROF with TIMED_STATISTICS, so that

one can see the CPU utilization, or with AUTOTRACE to see the statistics. Compare

this to the explain plan when not using an index.

When should one rebuild an index? (for DBA) You can run the 'ANALYZE INDEX VALIDATE STRUCTURE' command on the

affected indexes - each invocation of this command creates a single row in the

INDEX_STATS view. This row is overwritten by the next ANALYZE INDEX

command, so copy the contents of the view into a local table after each ANALYZE.

The 'badness' of the index can then be judged by the ratio of 'DEL_LF_ROWS' to

'LF_ROWS'.

What are the unrestricted procedures used to change the popup screen position

during run time ? Anchor-view

Resize -View

Move-View.

What is an Alert ? An alert is window that appears in the middle of the screen overlaying a portion of the

current display.

Deleting a page removes information about all the fields in that page ?

a. True. b. False a. True.

Two popup pages can appear on the screen at a time ?Two popup pages can

appear on the screen at a time ?

a. True. b. False? a. True.

Classify the restricted and unrestricted procedure from the following.

a. Call

© Copyright : IT Engg Portal – www.itportal.in 409

b. User-Exit

c. Call-Query

d. Up

e. Execute-Query

f. Message

g. Exit-From

h. Post

i. Break?

a. Call - unrestricted

b. User Exit - Unrestricted

c. Call_query - Unrestricted

d. Up - Restricted

e. Execute Query - Restricted

f. Message - Restricted

g. Exit_form - Restricted

h. Post - Restricted

i. Break - Unrestricted.

What is an User Exits ? A user exit is a subroutine which are written in programming languages using pro*C

pro *Cobol , etc., that link into the SQL * forms executable.

What is a Trigger ? A piece of logic that is executed at or triggered by a SQL *forms event.

What is a Package Procedure ? A Package procedure is built in PL/SQL procedure.

What is the maximum size of a form ? 255 character width and 255 characters Length.

What is the difference between system.current_field and system.cursor_field ? 1. System.current_field gives name of the field.

2. System.cursor_field gives name of the field with block name.

List the system variables related in Block and Field? 1. System.block_status

© Copyright : IT Engg Portal – www.itportal.in 410

2. System.current_block

3. System.current_field

4. System.current_value

5. System.cursor_block

6. System.cursor_field

7. System.field_status.

What are the different types of Package Procedure ? 1. Restricted package procedure.

2. Unrestricted package procedure.

What are the types of TRIGGERS ? 1. Navigational Triggers.

2. Transaction Triggers.

Identify package function from the following ?

1. Error-Code

2. Break

3. Call

4. Error-text

5. Form-failure

6. Form-fatal

7. Execute-query

8. Anchor View

9. Message_code?

1. Error_Code

2. Error_Text

3. Form_Failure

4. Form_Fatal

5. Message_Code

Can you attach an lov to a field at run-time? if yes, give the build-in name.? Yes. Set_item_proprety

Is it possible to attach same library to more than one form? Yes

© Copyright : IT Engg Portal – www.itportal.in 411

Can you attach an lov to a field at design time? Yes

List the windows event triggers available in Forms 4.0? When-window-activated,

when-window-closed,

when-window-deactivated,

when-window-resized

What are the triggers associated with the image item? When-Image-activated(Fires when the operator double clicks on an image Items)

When-image-pressed(fires when the operator selects or deselects the image item)

What is a visual attribute? Visual Attributes are the font, color and pattern characteristics of objects that operators

see and intract with in our application.

How many maximum number of radio buttons can you assign to a radio group? Unlimited no of radio buttons can be assigned to a radio group

How do you pass the parameters from one form to another form?

To pass one or more parameters to a called form, the calling form must perform the

following steps in a trigger or user named routine execute the create_parameter_list

built-in function to programmatically. Create a parameter list to execute the add

parameter built-in procedure to add one or more parameters list. Execute the

call_form, New_form or run_product built_in procedure and include the name or id of

the parameter list to be passed to the called form.

What is a Layout Editor? The Layout Editor is a graphical design facility for creating and arranging items and

boilerplate text and graphics objects in your application's interface.

List the Types of Items? Text item.

Chart item.

Check box.

Display item.

Image item.

© Copyright : IT Engg Portal – www.itportal.in 412

List item.

Radio Group.

User Area item.

List system variables available in forms 4.0, and not available in forms 3.0? System.cordination_operation

System Date_threshold

System.effective_Date

System.event_window

System.suppress_working

What are the display styles of an alert? Stop, Caution, note

What built-in is used for showing the alert during run-time? Show_alert.

What built-in is used for changing the properties of the window dynamically? Set_window_property

Canvas-View

What are the different types of windows? Root window, secondary window.

What is a predefined exception available in forms 4.0? Raise form_trigger_failure

What is a radio Group? Radio groups display a fixed no of options that are mutually Exclusive. User can select

one out of n number of options.

What are the different type of a record group? Query record group

Static record group

Non query record group

What are the menu items that oracle forms 4.0 supports? Plain, Check,Radio, Separator, Magic

© Copyright : IT Engg Portal – www.itportal.in 413

Give the equivalent term in forms 4.0 for the following. Page, Page 0? Page - Canvas-View

Page 0 - Canvas-view null.

What triggers are associated with the radio group? Only when-radio-changed trigger associated with radio group

Visual Attributes.

What are the triggers associated with a check box? Only When-checkbox-activated Trigger associated with a Check box.

Can you attach an alert to a field? No

Can a root window be made modal? No

What is a list item? It is a list of text elements.

List some built-in routines used to manipulate images in image_item? Image_add

Image_and

Image_subtract

Image_xor

Image_zoom

Can you change the alert messages at run-time? If yes, give the name of the built-in to change the alert messages at run-time. Yes.

Set_alert_property.

What is the built-in used to get and set lov properties during run-time? Get_lov_property

Set_lov_property

Record Group

What is the built-in routine used to count the no of rows in a group? Get_group _row_count

System Variables

© Copyright : IT Engg Portal – www.itportal.in 414

Give the Types of modules in a form? Form

Menu

Library

Write the Abbreviation for the following File Extension 1. FMB 2. MMB 3.

PLL? FMB ----- Form Module Binary.

MMB ----- Menu Module Binary.

PLL ------ PL/SQL Library Module Binary.

List the built-in routine for controlling window during run-time? Find_window,

get_window_property,

hide_window,

move_window,

resize_window,

set_window_property,

show_View

List the built-in routine for controlling window during run-time? Find_canvas

Get-Canvas_property

Get_view_property

Hide_View

Replace_content_view

Scroll_view

Set_canvas_property

Set_view_property

Show_view

Alert

What is the built-in function used for finding the alert? Find_alert

Editors

List the editors availables in forms 4.0? Default editor

© Copyright : IT Engg Portal – www.itportal.in 415

User_defined editors

system editors.

What buil-in routines are used to display editor dynamically? Edit_text item

show_editor

LOV

What is an Lov?

A list of values is a single or multi column selection list displayed in a pop-up window

What is a record Group? A record group is an internal oracle forms data structure that has a similar column/row

frame work to a database table

Give built-in routine related to a record groups? Create_group (Function)

Create_group_from_query(Function)

Delete_group(Procedure)

Add_group_column(Function)

Add_group_row(Procedure)

Delete_group_row(Procedure)

Populate_group(Function)

Populate_group_with_query(Function)

Set_group_Char_cell(procedure)

List the built-in routines for the controlling canvas views during run-time? Find_canvas

Get-Canvas_property

Get_view_property

Hide_View

Replace_content_view

Scroll_view

Set_canvas_property

Set_view_property

Show_view

Alert

© Copyright : IT Engg Portal – www.itportal.in 416

System.effective_date system variable is read only True/False? False

What are the built_in used to trapping errors in forms 4? Error_type return character

Error_code return number

Error_text return char

Dbms_error_code return no.

Dbms_error_text return char

What is Oracle Financials? (for DBA) Oracle Financials products provide organizations with solutions to a wide range of

long- and short-term accounting system issues. Regardless of the size of the business,

Oracle Financials can meet accounting management demands with:

Oracle Assets: Ensures that an organization's property and equipment investment is

accurate and that the correct asset tax accounting strategies are chosen.

Oracle General Ledger: Offers a complete solution to journal entry, budgeting,

allocations, consolidation, and financial reporting needs.

Oracle Inventory: Helps an organization make better inventory decisions by

minimizing stock and maximizing cash flow.

Oracle Order Entry: Provides organizations with a sophisticated order entry system for

managing customer commitments.

Oracle Payables: Lets an organization process more invoices with fewer staff members

and tighter controls. Helps save money through maximum discounts, bank float, and

prevention of duplicate payment.

Oracle Personnel: Improves the management of employee- related issues by retaining

and making available every form of personnel data.

Oracle Purchasing: Improves buying power, helps negotiate bigger discounts,

eliminates paper flow, increases financial controls, and increases productivity.

Oracle Receivables:. Improves cash flow by letting an organization process more

payments faster, without off-line research. Helps correctly account for cash, reduce

outstanding receivables, and improve collection effectiveness.

Oracle Revenue Accounting Gives an organization timely and accurate revenue and

flexible commissions reporting.

Oracle Sales Analysis: Allows for better forecasting, planning. and reporting of sales

information.

© Copyright : IT Engg Portal – www.itportal.in 417

What are the design facilities available in forms 4.0? Default Block facility.

Layout Editor.

Menu Editor.

Object Lists.

Property Sheets.

PL/SQL Editor.

Tables Columns Browser.

Built-ins Browser.

What is the most important module in Oracle Financials? (for DBA) The General Ledger (GL) module is the basis for all other Oracle Financial modules.

All other modules provide information to it. If you implement Oracle Financials, you

should switch your current GL system first.GL is relatively easy to implement. You

should go live with it first to give your implementation team a chance to be familiar

with Oracle Financials.

What are the types of canvas-views? Content View, Stacked View.

What is the MultiOrg and what is it used for? (for DBA) MultiOrg or Multiple Organizations Architecture allows multiple operating units and

their relationships to be defined within a single installation of Oracle Applications.

This keeps each operating unit's transaction data separate and secure.

Use the following query to determine if MuliOrg is intalled:

select multi_org_flag from fnd_product_groups;

What is the difference between Fields and FlexFields? (for DBA) A field is a position on a form that one uses to enter, view, update, or delete

information. A field prompt describes each field by telling what kind of information

appears in the field, or alternatively, what kind of information should be entered in the

field.

A flexfield is an Oracle Applications field made up of segments. Each segment has an

assigned name and a set of valid values. Oracle Applications uses flexfields to capture

information about your organization. There are two types of flexfields: key flexfields

and descriptive flexfields.

© Copyright : IT Engg Portal – www.itportal.in 418

Explain types of Block in forms4.0? Base table Blocks.

Control Blocks.

1. A base table block is one that is associated with a specific database table or view.

2. A control block is a block that is not associated with a database table. ITEMS

What is an Alert? An alert is a modal window that displays a message notifies the operator of some

application condition

What are the built-in routines is available in forms 4.0 to create and manipulate a

parameter list? Add_parameter

Create_Parameter_list

Delete_parameter

Destroy_parameter_list

Get_parameter_attr

Get_parameter_list

set_parameter_attr

What is a record Group? A record group is an internal oracle forms data structure that has a similar column/row

frame work to a database table

What is a Navigable item? A navigable item is one that operators can navigate to with the keyboard during

default navigation, or that Oracle forms can navigate to by executing a navigational

built-in procedure.

What is a library in Forms 4.0? A library is a collection of Pl/SQL program units, including user named procedures,

functions & packages

How image_items can be populate to field in forms 4.0? A fetch from a long raw database column PL/Sql assignment to executing the

read_image_file built_in procedure to get an image from the file system.

© Copyright : IT Engg Portal – www.itportal.in 419

What is the content view and stacked view? A content view is the "Base" view that occupies the entire content pane of the window

in which it is displayed. A stacked view differs from a content canvas view in that it is

not the base view for the window to which it is assigned

What is a Check Box?

A Check Box is a two state control that indicates whether a certain condition or value

is on or off, true or false. The display state of a check box is always either "checked"

or "unchecked".

What is a canvas-view? A canvas-view is the background object on which you layout the interface items (text-

items, check boxes, radio groups, and so on.) and boilerplate objects that operators see

and interact with as they run your form. At run-time, operators can see only those

items that have been assigned to a specific canvas. Each canvas, in term, must be

displayed in a specific window.

Explain the following file extension related to library? .pll,.lib,.pld

The library pll files is a portable design file comparable to an fmb form file

The library lib file is a plat form specific, generated library file comparable to a fmx

form file

The pld file is Txt format file and can be used for source controlling your library files

Parameter

Explain the usage of WHERE CURRENT OF clause in cursors ? WHERE CURRENT OF clause in an UPDATE,DELETE statement refers to the latest

row fetched from a cursor. Database Triggers

Name the tables where characteristics of Package, procedure and functions are

stored ? User_objects, User_Source and User_error.

Explain the two type of Cursors ? There are two types of cursors, Implicit Cursor and Explicit Cursor. PL/SQL uses

Implicit Cursors for queries. User defined cursors are called Explicit Cursors. They

can be declared and used.

© Copyright : IT Engg Portal – www.itportal.in 420

What are two parts of package ? The two parts of package are PACKAGE SPECIFICATION & PACKAGE BODY.

Package Specification contains declarations that are global to the packages and local to

the schema. Package Body contains actual procedures and local declaration of the

procedures and cursor declarations.

What are two virtual tables available during database trigger execution ? The table columns are referred as OLD.column_name and NEW.column_name.

For triggers related to INSERT only NEW.column_name values only available.

For triggers related to UPDATE only OLD.column_name NEW.column_name values

only available.

For triggers related to DELETE only OLD.column_name values only available.

What is Fine Grained Auditing? (for DBA) Fine Grained Auditing (DBMS_FGA) allows auditing records to be generated when

certain rows are selected from a table. A list of defined policies can be obtained from

DBA_AUDIT_POLICIES. Audit records are stored in DBA_FGA_AUDIT_TRAIL.

Look at this example:

o Add policy on table with autiting condition...

execute dbms_fga.add_policy('HR', 'EMP', 'policy1', 'deptno > 10');

o Must ANALYZE, this feature works with CBO (Cost Based Optimizer)

analyze table EMP compute statistics;

select * from EMP where c1 = 11; -- Will trigger auditing

select * from EMP where c1 = 09; -- No auditing

o Now we can see the statments that triggered the auditing condition...

select sqltext from sys.fga_log$;

delete from sys.fga_log$;

What is a package ? What are the advantages of packages ? What is Pragma

EXECPTION_INIT ? Explain the usage ? The PRAGMA EXECPTION_INIT tells the complier to associate an exception with

an oracle error. To get an error message of a specific oracle error. e.g. PRAGMA

EXCEPTION_INIT (exception name, oracle error number)

What is a Virtual Private Database? (for DBA) Oracle 8i introduced the notion of a Virtual Private Database (VPD). A VPD offers

Fine-Grained Access Control (FGAC) for secure separation of data. This ensures that

users only have access to data that pertains to them. Using this option, one could even

© Copyright : IT Engg Portal – www.itportal.in 421

store multiple companies' data within the same schema, without them knowing about

it. VPD configuration is done via the DBMS_RLS (Row Level Security) package.

Select from SYS.V$VPD_POLICY to see existing VPD configuration.

What is Raise_application_error ? Raise_application_error is a procedure of package DBMS_STANDARD which allows

to issue an user_defined error messages from stored sub-program or database trigger.

What is Oracle Label Security? (for DBA) Oracle Label Security (formerly called Trusted Oracle MLS RDBMS) uses the VPD

(Virtual Private Database) feature of Oracle8i to implement row level security. Access

to rows are restricted according to a user's security sensitivity tag or label. Oracle

Label Security is configured, controlled and managed from the Policy Manager, an

Enterprise Manager-based GUI utility.

Give the structure of the procedure ? PROCEDURE name (parameter list.....)

is

local variable declarations

BEGIN

Executable statements.

Exception.

exception handlers

end;

What is OEM (Oracle Enterprise Manager)? (for DBA) OEM is a set of systems management tools provided by Oracle Corporation for

managing the Oracle environment. It provides tools to monitor the Oracle environment

and automate tasks (both one-time and repetitive in nature) to take database

administration a step closer to "Lights Out" management.

Question What is PL/SQL ? PL/SQL is a procedural language that has both interactive SQL and procedural

programming language constructs such as iteration, conditional branching.

What are the components of OEM? (for DBA) Oracle Enterprise Manager (OEM) has the following components:

. Management Server (OMS): Middle tier server that handles communication with the

© Copyright : IT Engg Portal – www.itportal.in 422

intelligent agents. The OEM Console connects to the management server to monitor

and configure the Oracle enterprise.

. Console: This is a graphical interface from where one can schedule jobs, events, and

monitor the database. The console can be opened from a Windows workstation, Unix

XTerm (oemapp command) or Web browser session (oem_webstage).

. Intelligent Agent (OIA): The OIA runs on the target database and takes care of the

execution of jobs and events scheduled through the Console.

What happens if a procedure that updates a column of table X is called in a

database trigger of the same table ? Mutation of table occurs.

Is it possible to use Transaction control Statements such a ROLLBACK or

COMMIT in Database Trigger ? Why ? It is not possible. As triggers are defined for each table, if you use COMMIT of

ROLLBACK in a trigger, it affects logical transaction processing.

How many types of database triggers can be specified on a table ? What are they

? Insert Update Delete

Before Row o.k. o.k. o.k.

After Row o.k. o.k. o.k.

Before Statement o.k. o.k. o.k.

After Statement o.k. o.k. o.k.

If FOR EACH ROW clause is specified, then the trigger for each Row affected by the

statement.

If WHEN clause is specified, the trigger fires according to the returned Boolean value.

What are the modes of parameters that can be passed to a procedure ? IN,OUT,IN-OUT parameters.

Where the Pre_defined_exceptions are stored ? In the standard package.

Procedures, Functions & Packages ;

Write the order of precedence for validation of a column in a table ?

I. done using Database triggers.

ii. done using Integarity Constraints.?

© Copyright : IT Engg Portal – www.itportal.in 423

I & ii.

Give the structure of the function ? FUNCTION name (argument list .....) Return datatype is

local variable declarations

Begin

executable statements

Exception

execution handlers

End;

Explain how procedures and functions are called in a PL/SQL block ? Function is called as part of an expression.

sal := calculate_sal ('a822');

procedure is called as a PL/SQL statement

calculate_bonus ('A822');

What are advantages fo Stored Procedures? Extensibility,Modularity, Reusability, Maintainability and one time compilation.

What is an Exception ? What are types of Exception ? Exception is the error handling part of PL/SQL block. The types are Predefined and

user defined. Some of Predefined exceptions are.

CURSOR_ALREADY_OPEN

DUP_VAL_ON_INDEX

NO_DATA_FOUND

TOO_MANY_ROWS

INVALID_CURSOR

INVALID_NUMBER

LOGON_DENIED

NOT_LOGGED_ON

PROGRAM-ERROR

STORAGE_ERROR

TIMEOUT_ON_RESOURCE

VALUE_ERROR

ZERO_DIVIDE

OTHERS.

© Copyright : IT Engg Portal – www.itportal.in 424

What are the PL/SQL Statements used in cursor processing ?

DECLARE CURSOR name, OPEN cursor name, FETCH cursor name INTO or

Record types, CLOSE cursor name.

What are the components of a PL/SQL Block ? Declarative part, Executable part and Exception part.

Datatypes PL/SQL

What is a database trigger ? Name some usages of database trigger ? Database trigger is stored PL/SQL program unit associated with a specific database

table. Usages are Audit data modifications, Log events transparently, Enforce complex

business rules Derive column values automatically, Implement complex security

authorizations. Maintain replicate tables.

What is a cursor ? Why Cursor is required ? Cursor is a named private SQL area from where information can be accessed. Cursors

are required to process rows individually for queries returning multiple rows.

What is a cursor for loop ? Cursor for loop implicitly declares %ROWTYPE as loop index, opens a cursor,

fetches rows of values from active set into fields in the record and closes when all the

records have been processed.

e.g.. FOR emp_rec IN C1 LOOP

salary_total := salary_total +emp_rec sal;

END LOOP;

What will happen after commit statement ? Cursor C1 is

Select empno,

ename from emp;

Begin

open C1; loop

Fetch C1 into

eno.ename;

Exit When

C1 %notfound;-----

commit;

end loop;

© Copyright : IT Engg Portal – www.itportal.in 425

end;

The cursor having query as SELECT .... FOR UPDATE gets closed after

COMMIT/ROLLBACK.

The cursor having query as SELECT.... does not get closed even after

COMMIT/ROLLBACK.

How packaged procedures and functions are called from the following?

a. Stored procedure or anonymous block

b. an application program such a PRC *C, PRO* COBOL

c. SQL *PLUS??

a. PACKAGE NAME.PROCEDURE NAME (parameters);

variable := PACKAGE NAME.FUNCTION NAME (arguments);

EXEC SQL EXECUTE

b.BEGIN

PACKAGE NAME.PROCEDURE NAME (parameters)

variable := PACKAGE NAME.FUNCTION NAME (arguments);

END;

END EXEC;

c. EXECUTE PACKAGE NAME.PROCEDURE if the procedures does not have any

out/in-out parameters. A function can not be called.

What is a stored procedure ? A stored procedure is a sequence of statements that perform specific function.

What are the components of a PL/SQL block ? A set of related declarations and procedural statements is called block.

What is difference between a PROCEDURE & FUNCTION ? A FUNCTION is always returns a value using the return statement.

A PROCEDURE may return one or more values through parameters or may not return

at all.

What is difference between a Cursor declared in a procedure and Cursor

declared in a package specification ? A cursor declared in a package specification is global and can be accessed by other

procedures or procedures in a package.

© Copyright : IT Engg Portal – www.itportal.in 426

A cursor declared in a procedure is local to the procedure that can not be accessed by

other procedures.

What are the cursor attributes used in PL/SQL ? %ISOPEN - to check whether cursor is open or not

% ROWCOUNT - number of rows fetched/updated/deleted.

% FOUND - to check whether cursor has fetched any row. True if rows are fetched.

% NOT FOUND - to check whether cursor has fetched any row. True if no rows are

featched.

These attributes are proceeded with SQL for Implicit Cursors and with Cursor name

for Explicit Cursors.

What are % TYPE and % ROWTYPE ? What are the advantages of using these

over datatypes? % TYPE provides the data type of a variable or a database column to that variable.

% ROWTYPE provides the record type that represents a entire row of a table or view

or columns selected in the cursor.

The advantages are :

I. Need not know about variable's data type

ii. If the database definition of a column in a table changes, the data type of a variable

changes accordingly.

What is difference between % ROWTYPE and TYPE RECORD ?

% ROWTYPE is to be used whenever query returns a entire row of a table or view.

TYPE rec RECORD is to be used whenever query returns columns of different table

or views and variables.

E.g. TYPE r_emp is RECORD (eno emp.empno% type,ename emp ename %type );

e_rec emp% ROWTYPE

cursor c1 is select empno,deptno from emp;

e_rec c1 %ROWTYPE.

What are the different types of PL/SQL program units that can be defined and

stored in ORACLE database ? Procedures and Functions,Packages and Database Triggers.

What are the advantages of having a Package ? Increased functionality (for example,global package variables can be declared and

© Copyright : IT Engg Portal – www.itportal.in 427

used by any proecdure in the package) and performance (for example all objects of the

package are parsed compiled, and loaded into memory once)

What are the uses of Database Trigger ? Database triggers can be used to automatic data generation, audit data modifications,

enforce complex Integrity constraints, and customize complex security authorizations.

What is a Procedure ? A Procedure consist of a set of SQL and PL/SQL statements that are grouped together

as a unit to solve a specific problem or perform a set of related tasks.

What is a Package ? A Package is a collection of related procedures, functions, variables and other package

constructs together as a unit in the database.

What is difference between Procedures and Functions ? A Function returns a value to the caller where as a Procedure does not.

What is Database Trigger ? A Database Trigger is procedure (set of SQL and PL/SQL statements) that is

automatically executed as a result of an insert in, update to, or delete from a table.

Can the default values be assigned to actual parameters? Yes

Can a primary key contain more than one columns? Yes

What is an UTL_FILE.What are different procedures and functions associated

with it? UTL_FILE is a package that adds the ability to read and write to operating system

files. Procedures associated with it are FCLOSE, FCLOSE_ALL and 5 procedures to

output data to a file PUT, PUT_LINE, NEW_LINE, PUTF, FFLUSH.PUT,

FFLUSH.PUT_LINE,FFLUSH.NEW_LINE. Functions associated with it are FOPEN,

ISOPEN.

What are ORACLE PRECOMPILERS? Using ORACLE PRECOMPILERS, SQL statements and PL/SQL blocks can be

contained inside 3GL programs written in C,C++,COBOL,PASCAL, FORTRAN,PL/1

© Copyright : IT Engg Portal – www.itportal.in 428

AND ADA. The Precompilers are known as Pro*C,Pro*Cobol,... This form of

PL/SQL is known as embedded pl/sql,the language in which pl/sql is embedded is

known as the host language. The prcompiler translates the embedded SQL and pl/sql

statements into calls to the precompiler runtime library. The output must be compiled

and linked with this library to creator an executable.

Differentiate between TRUNCATE and DELETE? TRUNCATE deletes much faster than DELETE

TRUNCATE

DELETE

It is a DDL statement

It is a DML statement

It is a one way trip, cannot ROLLBACK

One can Rollback

Doesn't have selective features (where clause)

Has

Doesn't fire database triggers

Does

It requires disabling of referential constraints.

What is difference between a formal and an actual parameter? The variables declared in the procedure and which are passed, as arguments are called

actual, the parameters in the procedure declaration. Actual parameters contain the

values that are passed to a procedure and receive results. Formal parameters are the

placeholders for the values of actual parameters

What should be the return type for a cursor variable. Can we use a scalar data

type as return type?

The return type for a cursor must be a record type.It can be declared explicitly as a

user-defined or %ROWTYPE can be used. eg TYPE t_studentsref IS REF CURSOR

RETURN students%ROWTYPE

What are different Oracle database objects? -TABLES

-VIEWS

-INDEXES

-SYNONYMS

© Copyright : IT Engg Portal – www.itportal.in 429

-SEQUENCES

-TABLESPACES etc

What is difference between SUBSTR and INSTR? SUBSTR returns a specified portion of a string eg SUBSTR('BCDEF',4) output BCDE

INSTR provides character position in which a pattern is found in a string. eg

INSTR('ABC-DC-F','-',2) output 7 (2nd occurence of '-')

Display the number value in Words? SQL> select sal, (to_char(to_date(sal,'j'), 'jsp'))

from emp;

the output like,

SAL (TO_CHAR(TO_DATE(SAL,'J'),'JSP'))

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

800 eight hundred

1600 one thousand six hundred

1250 one thousand two hundred fifty

If you want to add some text like, Rs. Three Thousand only.

SQL> select sal "Salary ",

(' Rs. '|| (to_char(to_date(sal,'j'), 'Jsp'))|| ' only.'))

"Sal in Words" from emp

/

Salary Sal in Words

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

800 Rs. Eight Hundred only.

1600 Rs. One Thousand Six Hundred only.

1250 Rs. One Thousand Two Hundred Fifty only.

What is difference between SQL and SQL*PLUS? SQL*PLUS is a command line tool where as SQL and PL/SQL language interface and

reporting tool. Its a command line tool that allows user to type SQL commands to be

executed directly against an Oracle database. SQL is a language used to query the

relational database(DML,DCL,DDL). SQL*PLUS commands are used to format

query result, Set options, Edit SQL commands and PL/SQL.

What are various joins used while writing SUBQUERIES? Self join-Its a join foreign key of a table references the same table. Outer Join--Its a

join condition used where One can query all the rows of one of the tables in the join

© Copyright : IT Engg Portal – www.itportal.in 430

condition even though they don't satisfy the join condition.

Equi-join--Its a join condition that retrieves rows from one or more tables in which

one or more columns in one table are equal to one or more columns in the second

table.

What a SELECT FOR UPDATE cursor represent.? SELECT......FROM......FOR......UPDATE[OF column-reference][NOWAIT]

The processing done in a fetch loop modifies the rows that have been retrieved by the

cursor. A convenient way of modifying the rows is done by a method with two parts:

the FOR UPDATE clause in the cursor declaration, WHERE CURRENT OF

CLAUSE in an UPDATE or declaration statement.

What are various privileges that a user can grant to another user? -SELECT

-CONNECT

-RESOURCES

Display the records between two range? select rownum, empno, ename from emp where rowid in (select rowid from emp

where rownum <=&upto minus select rowid from emp where rownum<&Start);

minvalue.sql Select the Nth lowest value from a table?

select level, min('col_name') from my_table where level = '&n' connect by prior

('col_name') < 'col_name')

group by level;

Example:

Given a table called emp with the following columns:

-- id number

-- name varchar2(20)

-- sal number

--

-- For the second lowest salary:

-- select level, min(sal) from emp

-- where level=2

-- connect by prior sal < sal

-- group by level

© Copyright : IT Engg Portal – www.itportal.in 431

What is difference between Rename and Alias? Rename is a permanent name given to a table or column whereas Alias is a temporary

name given to a table or column which do not exist once the SQL statement is

executed.

Difference between an implicit & an explicit cursor.? only one row. However,queries that return more than one row you must declare an

explicit cursor or use a cursor FOR loop. Explicit cursor is a cursor in which the cursor

name is explicitly assigned to a SELECT statement via the CURSOR...IS statement.

An implicit cursor is used for all SQL statements Declare, Open, Fetch, Close. An

explicit cursors are used to process multirow SELECT statements An implicit cursor is

used to process INSERT, UPDATE, DELETE and single row SELECT. .INTO

statements.

What is a OUTER JOIN? Outer Join--Its a join condition used where you can query all the rows of one of the

tables in the join condition even though they don‘t satisfy the join condition.

What is a cursor? Oracle uses work area to execute SQL statements and store processing information

PL/SQL construct called a cursor lets you name a work area and access its stored

information A cursor is a mechanism used to fetch more than one row in a Pl/SQl

block.

What is the purpose of a cluster? Oracle does not allow a user to specifically locate tables, since that is a part of the

function of the RDBMS. However, for the purpose of increasing performance, oracle

allows a developer to create a CLUSTER. A CLUSTER provides a means for storing

data from different tables together for faster retrieval than if the table placement were

left to the RDBMS.

What is OCI. What are its uses? Oracle Call Interface is a method of accesing database from a 3GL program. Uses--No

precompiler is required,PL/SQL blocks are executed like other DML statements.

The OCI library provides

--functions to parse SQL statemets

--bind input variables

--bind output variables

© Copyright : IT Engg Portal – www.itportal.in 432

--execute statements

--fetch the results

How you open and close a cursor variable. Why it is required? OPEN cursor variable FOR SELECT...Statement

CLOSE cursor variable In order to associate a cursor variable with a particular

SELECT statement OPEN syntax is used. In order to free the resources used for the

query CLOSE statement is used.

Display Odd/ Even number of records? Odd number of records:

select * from emp where (rowid,1) in (select rowid, mod(rownum,2) from emp);

Output:-

1

3

5

Even number of records:

select * from emp where (rowid,0) in (select rowid, mod(rownum,2) from emp)

Output:-

2

4

6

What are various constraints used in SQL? -NULL

-NOT NULL

-CHECK

-DEFAULT

Can cursor variables be stored in PL/SQL tables. If yes how. If not why? No, a cursor variable points a row which cannot be stored in a two-dimensional

PL/SQL table.

Difference between NO DATA FOUND and %NOTFOUND? NO DATA FOUND is an exception raised only for the SELECT....INTO statements

when the where clause of the querydoes not match any rows. When the where clause

of the explicit cursor does not match any rows the %NOTFOUND attribute is set to

TRUE instead.

© Copyright : IT Engg Portal – www.itportal.in 433

Can you use a commit statement within a database trigger? No

What WHERE CURRENT OF clause does in a cursor? LOOP

SELECT num_credits INTO v_numcredits FROM classes

WHERE dept=123 and course=101;

UPDATE students

FHKO;;;;;;;;;SET current_credits=current_credits+v_numcredits

WHERE CURRENT OF X;

There is a string 120000 12 0 .125 , how you will find the position of the decimal

place? INSTR('120000 12 0 .125',1,'.')

output 13

What are different modes of parameters used in functions and procedures? -IN -OUT -INOUT

How you were passing cursor variables in PL/SQL 2.2? In PL/SQL 2.2 cursor variables cannot be declared in a package.This is because the

storage for a cursor variable has to be allocated using Pro*C or OCI with version 2.2,

the only means of passing a cursor variable to a PL/SQL block is via bind variable or a

procedure parameter.

When do you use WHERE clause and when do you use HAVING clause? HAVING clause is used when you want to specify a condition for a group function

and it is written after GROUP BY clause. The WHERE clause is used when you want

to specify a condition for columns, single row functions except group functions and it

is written before GROUP BY clause if it is used.

Difference between procedure and function.? Functions are named PL/SQL blocks that return a value and can be called with

arguments procedure a named block that can be called with parameter. A procedure all

is a PL/SQL statement by itself, while a Function call is called as part of an

expression.

© Copyright : IT Engg Portal – www.itportal.in 434

Which is more faster - IN or EXISTS? EXISTS is more faster than IN because EXISTS returns a Boolean value whereas IN

returns a value.

What is syntax for dropping a procedure and a function .Are these operations

possible?

Drop Procedure procedure_name

Drop Function function_name

How will you delete duplicating rows from a base table? delete from table_name where rowid not in (select max(rowid) from table group by

duplicate_values_field_name); or delete duplicate_values_field_name dv from

table_name ta where rowid <(select min(rowid) from table_name tb where

ta.dv=tb.dv);

Difference between database triggers and form triggers? -Data base trigger(DBT) fires when a DML operation is performed on a data base

table. Form trigger(FT) Fires when user presses a key or navigates between fields on

the screen

-Can be row level or statement level No distinction between row level and statement

level.

-Can manipulate data stored in Oracle tables via SQL Can manipulate data in Oracle

tables as well as variables in forms.

-Can be fired from any session executing the triggering DML statements. Can be fired

only from the form that define the trigger.

-Can cause other database triggers to fire. Can cause other database triggers to fire, but

not other form triggers.

What is a cursor for loop? Cursor For Loop is a loop where oracle implicitly declares a loop variable, the loop

index that of the same record type as the cursor's record.

How you will avoid duplicating records in a query? By using DISTINCT

What is a view ? A view is stored procedure based on one or more tables, it‘s a virtual table.

© Copyright : IT Engg Portal – www.itportal.in 435

What is difference between UNIQUE and PRIMARY KEY constraints? A table can have only one PRIMARY KEY whereas there can be any number of

UNIQUE keys. The columns that compose PK are automatically define NOT NULL,

whereas a column that compose a UNIQUE is not automatically defined to be

mandatory must also specify the column is NOT NULL.

What is use of a cursor variable? How it is defined? A cursor variable is associated with different statements at run time, which can hold

different values at run time. Static cursors can only be associated with one run time

query. A cursor variable is reference type (like a pointer in C).

Declaring a cursor variable:

TYPE type_name IS REF CURSOR RETURN return_type type_name is the name of

the reference type,return_type is a record type indicating the types of the select list that

will eventually be returned by the cursor variable.

How do you find the numbert of rows in a Table ? A bad answer is count them (SELECT COUNT(*) FROM table_name)

A good answer is :-

'By generating SQL to ANALYZE TABLE table_name COUNT STATISTICS by

querying Oracle System Catalogues (e.g. USER_TABLES or ALL_TABLES).

The best answer is to refer to the utility which Oracle released which makes it

unnecessary to do ANALYZE TABLE for each Table individually.

What is the maximum buffer size that can be specified using the

DBMS_OUTPUT.ENABLE function? 1,000,00

What are cursor attributes? -%ROWCOUNT

-%NOTFOUND

-%FOUND

-%ISOPEN

There is a % sign in one field of a column. What will be the query to find it? '' Should be used before '%'.

What is ON DELETE CASCADE ? When ON DELETE CASCADE is specified ORACLE maintains referential integrity

© Copyright : IT Engg Portal – www.itportal.in 436

by automatically removing dependent foreign key values if a referenced primary or

unique key value is removed.

What is the fastest way of accessing a row in a table ? Using ROWID.CONSTRAINTS

What is difference between TRUNCATE & DELETE ? TRUNCATE commits after deleting entire table i.e., can not be rolled back. Database

triggers do not fire on TRUNCATEDELETE allows the filtered deletion. Deleted

records can be rolled back or committed. Database triggers fire on DELETE.

What is a transaction ? Transaction is logical unit between two commits and commit and rollback.

What are the advantages of VIEW ?

To protect some of the columns of a table from other users.To hide complexity of a

query.To hide complexity of calculations.

How will you a activate/deactivate integrity constraints ? The integrity constraints can be enabled or disabled by ALTER TABLE ENABLE

constraint/DISABLE constraint.

Where the integrity constraints are stored in Data Dictionary ? The integrity constraints are stored in USER_CONSTRAINTS.

What is the Subquery ? Sub query is a query whose return values are used in filtering conditions of the main

query.

How to access the current value and next value from a sequence ? Is it possible to

access the current value in a session before accessing next value ? Sequence name CURRVAL, Sequence name NEXTVAL.It is not possible. Only if

you access next value in the session, current value can be accessed.

What are the usage of SAVEPOINTS ?value in a session before accessing next

value ? SAVEPOINTS are used to subdivide a transaction into smaller parts. It enables rolling

back part of a transaction. Maximum of five save points are allowed.

© Copyright : IT Engg Portal – www.itportal.in 437

What is ROWID ?in a session before accessing next value ? ROWID is a pseudo column attached to each row of a table. It is 18 character long,

blockno, rownumber are the components of ROWID.

Explain Connect by Prior ?in a session before accessing next value ? Retrieves rows in hierarchical order.e.g. select empno, ename from emp where.

How many LONG columns are allowed in a table ? Is it possible to use LONG

columns in WHERE clause or ORDER BY ? Only one LONG columns is allowed. It is not possible to use LONG column in

WHERE or ORDER BY clause.

What is Referential Integrity ? Maintaining data integrity through a set of rules that restrict the values of one or more

columns of the tables based on the values of primary key or unique key of the

referenced table.

What is a join ? Explain the different types of joins ? Join is a query which retrieves related columns or rows from multiple tables.Self Join -

Joining the table with itself.Equi Join - Joining two tables by equating two common

columns.Non-Equi Join - Joining two tables by equating two common columns.Outer

Join - Joining two tables in such a way that query can also retrieve rows that do not

have corresponding join value in the other table.

If an unique key constraint on DATE column is created, will it validate the rows

that are inserted with SYSDATE ? It won't, Because SYSDATE format contains time attached with it.

How does one stop and start the OMS? (for DBA)

Use the following command sequence to stop and start the OMS (Oracle Management

Server):

oemctl start oms

oemctl status oms sysman/oem_temp

oemctl stop oms sysman/oem_temp

Windows NT/2000 users can just stop and start the required services. The default

OEM administrator is "sysman" with a password of "oem_temp".

NOTE: Use command oemctrl instead of oemctl for Oracle 8i and below.

© Copyright : IT Engg Portal – www.itportal.in 438

What is an Integrity Constraint ? Integrity constraint is a rule that restricts values to a column in a table.

How does one create a repository? (for DBA) For OEM v2 and above, start the Oracle Enterprise Manager Configuration Assistant

(emca on Unix) to create and configure the management server and repository.

Remember to setup a backup for the repository database after creating it.

If a View on a single base table is manipulated will the changes be reflected on the

base table ? If changes are made to the tables which are base tables of a view will the changes be

reference on the view.

The following describes means to create a OEM V1.x (very old!!!) repository on

WindowsNT:

. Create a tablespace that would hold the repository data. A size between 200- 250 MB

would be ideal. Let us call it Dummy_Space.

. Create an Oracle user who would own this repository. Assign DBA, SNMPAgent,

Exp_Full_database, Imp_Full_database roles to this user. Lets call this user

Dummy_user. Assign Dummy_Space as the default tablespace.

. Create an operating system user with the same name as the Oracle username. I.e.

Dummy_User. Add 'Log on as a batch job' under advanced rights in User manager.

. Fire up Enterprise manager and log in as Dummy_User and enter the password. This

would trigger the creation of the repository. From now on, Enterprise manager is ready

to accept jobs.

What is a database link ? Database Link is a named path through which a remote database can be accessed.

How does one list one's databases in the OEM Console? (for DBA) Follow these steps to discover databases and other services from the OEM Console:

1. Ensure the GLOBAL_DBNAME parameter is set for all databases in your

LISTENER.ORA file (optional). These names will be listed in the OEM Console.

Please note that names entered are case sensitive. A portion of a listener.ora file:

(SID_DESC =

(GLOBAL_DBNAME = DB_name_for_OEM)

(SID_NAME = ...

© Copyright : IT Engg Portal – www.itportal.in 439

2. Start the Oracle Intelligent Agent on the machine you want to discover. See section

"How does one start the Oracle Intelligent Agent?".

3. Start the OEM Console, navigate to menu "Navigator/ Discover Nodes". The OEM

Discovery Wizard will guide you through the process of discovering your databases

and other services.

What is CYCLE/NO CYCLE in a Sequence ? CYCLE specifies that the sequence continues to generate values after reaching either

maximum or minimum value. After pan ascending sequence reaches its maximum

value, it generates its minimum value. After a descending sequence reaches its

minimum, it generates its maximum.NO CYCLE specifies that the sequence cannot

generate more values after reaching its maximum or minimum value.

What is correlated sub-query ? Correlated sub query is a sub query which has reference to the main query.

What are the data types allowed in a table ? CHAR,VARCHAR2,NUMBER,DATE,RAW,LONG and LONG RAW.

What is difference between CHAR and VARCHAR2 ? What is the maximum

SIZE allowed for each type ? CHAR pads blank spaces to the maximum length. VARCHAR2 does not pad blank

spaces. For CHAR it is 255 and 2000 for VARCHAR2.

Can a view be updated/inserted/deleted? If Yes under what conditions ? A View can be updated/deleted/inserted if it has only one base table if the view is

based on columns from one or more tables then insert, update and delete is not

possible.

What are the different types of Coordinations of the Master with the Detail

block? POPULATE_GROUP(function)

POPULATE_GROUP_WITH_QUERY(function)

SET_GROUP_CHAR_CELL(procedure)

SET_GROUPCELL(procedure)

SET_GROUP_NUMBER_CELL(procedure)

© Copyright : IT Engg Portal – www.itportal.in 440

Use the ADD_GROUP_COLUMN function to add a column to a record group

that was created at design time?

I) TRUE II) FALSE II) FALSE

Use the ADD_GROUP_ROW procedure to add a row to a static record group?

I) TRUE II) FALSE I) FALSE

maxvalue.sql Select the Nth Highest value from a table? select level, max('col_name') from my_table where level = '&n' connect by prior

('col_name') > 'col_name')

group by level;

Example:

Given a table called emp with the following columns:

-- id number

-- name varchar2(20)

-- sal number

--

-- For the second highest salary:

-- select level, max(sal) from emp

-- where level=2

-- connect by prior sal > sal

-- group by level

Find out nth highest salary from emp table? SELECT DISTINCT (a.sal) FROM EMP A WHERE &N = (SELECT COUNT

(DISTINCT (b.sal)) FROM EMP B WHERE a.sal<=b.sal);

For E.g.:-

Enter value for n: 2

SAL

---------

3700

Suppose a customer table is having different columns like customer no,

payments.What will be the query to select top three max payments? SELECT customer_no, payments from customer C1

© Copyright : IT Engg Portal – www.itportal.in 441

WHERE 3<=(SELECT COUNT(*) from customer C2

WHERE C1.payment <= C2.payment)

How you will avoid your query from using indexes? SELECT * FROM emp

Where emp_no+' '=12345;

i.e you have to concatenate the column name with space within codes in the where

condition.

SELECT /*+ FULL(a) */ ename, emp_no from emp

where emp_no=1234;

i.e using HINTS

What utility is used to create a physical backup? Either rman or alter tablespace begin backup will do..

What are the Back ground processes in Oracle and what are they. This is one of the most frequently asked question.There are basically 9 Processes but

in a general system we need to mention the first five background processes.They do

the house keeping activities for the Oracle and are common in any system.

The various background processes in oracle are

a) Data Base Writer(DBWR) :: Data Base Writer Writes Modified blocks from

Database buffer cache to Data Files.This is required since the data is not written

whenever a transaction is committed.

b)LogWriter(LGWR) :: LogWriter writes the redo log entries to disk. Redo Log data is

generated in redo log buffer of SGA. As transaction commits and log buffer fills,

LGWR writes log entries into a online redo log file.

c) System Monitor(SMON) :: The System Monitor performs instance recovery at

instance startup. This is useful for recovery from system failure

d)Process Monitor(PMON) :: The Process Monitor performs process recovery when

user Process fails. Pmon Clears and Frees resources that process was using.

e) CheckPoint(CKPT) :: At Specified times, all modified database buffers in SGA are

written to data files by DBWR at Checkpoints and Updating all data files and control

files of database to indicate the most recent checkpoint

f)Archieves(ARCH) :: The Archiver copies online redo log files to archival storal

when they are busy.

g) Recoveror(RECO) :: The Recoveror is used to resolve the distributed transaction in

network

© Copyright : IT Engg Portal – www.itportal.in 442

h) Dispatcher (Dnnn) :: The Dispatcher is useful in Multi Threaded Architecture

i) Lckn :: We can have upto 10 lock processes for inter instance locking in parallel sql.

How many types of Sql Statements are there in Oracle There are basically 6 types of sql statments.They are

a) Data Definition Language(DDL) :: The DDL statements define and maintain

objects and drop objects.

b) Data Manipulation Language(DML) :: The DML statements manipulate database

data.

c) Transaction Control Statements :: Manage change by DML

d) Session Control :: Used to control the properties of current session enabling and

disabling roles and changing .e.g. :: Alter Statements, Set Role

e) System Control Statements :: Change Properties of Oracle Instance .e.g.:: Alter

System

f) Embedded Sql :: Incorporate DDL, DML and T.C.S in Programming Language.e.g::

Using the Sql Statements in languages such as 'C', Open, Fetch, execute and close

What is a Transaction in Oracle A transaction is a Logical unit of work that compromises one or more SQL Statements

executed by a single User. According to ANSI, a transaction begins with first

executable statement and ends when it is explicitly committed or rolled back.

Key Words Used in Oracle The Key words that are used in Oracle are ::

a) Committing :: A transaction is said to be committed when the transaction makes

permanent changes resulting from the SQL statements.

b) Rollback :: A transaction that retracts any of the changes resulting from SQL

statements in Transaction.

c) SavePoint :: For long transactions that contain many SQL statements, intermediate

markers or savepoints are declared. Savepoints can be used to divide a transaction into

smaller points.

d) Rolling Forward :: Process of applying redo log during recovery is called rolling

forward.

e) Cursor :: A cursor is a handle ( name or a pointer) for the memory associated with a

specific stamen. A cursor is basically an area allocated by Oracle for executing the Sql

Statement. Oracle uses an implicit cursor statement for Single row query and Uses

Explicit cursor for a multi row query.

© Copyright : IT Engg Portal – www.itportal.in 443

f) System Global Area(SGA) :: The SGA is a shared memory region allocated by the

Oracle that contains Data and control information for one Oracle Instance. It consists

of Database Buffer Cache and Redo log Buffer.

g) Program Global Area (PGA) :: The PGA is a memory buffer that contains data and

control information for server process.

g) Database Buffer Cache :: Database Buffer of SGA stores the most recently used

blocks of database data. The set of database buffers in an instance is called Database

Buffer Cache.

h) Redo log Buffer :: Redo log Buffer of SGA stores all the redo log entries.

i) Redo Log Files :: Redo log files are set of files that protect altered database data in

memory that has not been written to Data Files. They are basically used for backup

when a database crashes.

j) Process :: A Process is a 'thread of control' or mechanism in Operating System that

executes series of steps.

What are Procedure, functions and Packages ?

Procedures and functions consist of set of PL/SQL statements that are grouped

together as a unit to solve a specific problem or perform set of related tasks.

Procedures do not Return values while Functions return one One Value Packages ::

Packages Provide a method of encapsulating and storing related procedures, functions,

variables and other Package Contents

What are Database Triggers and Stored Procedures Database Triggers :: Database Triggers are Procedures that are automatically executed

as a result of insert in, update to, or delete from table.

Database triggers have the values old and new to denote the old value in the table

before it is deleted and the new indicated the new value that will be used. DT are

useful for implementing complex business rules which cannot be enforced using the

integrity rules.We can have the trigger as Before trigger or After Trigger and at

Statement or Row level. e.g:: operations insert,update ,delete 3 before ,after 3*2 A

total of 6 combinatons

At statment level(once for the trigger) or row level( for every execution ) 6 * 2 A total

of 12. Thus a total of 12 combinations are there and the restriction of usage of 12

triggers has been lifted from Oracle 7.3 Onwards.

Stored Procedures :: Stored Procedures are Procedures that are stored in Compiled

form in the database.The advantage of using the stored procedures is that many users

can use the same procedure in compiled and ready to use format.

© Copyright : IT Engg Portal – www.itportal.in 444

How many Integrity Rules are there and what are they There are Three Integrity Rules. They are as follows ::

a) Entity Integrity Rule :: The Entity Integrity Rule enforces that the Primary key

cannot be Null

b) Foreign Key Integrity Rule :: The FKIR denotes that the relationship between the

foreign key and the primary key has to be enforced.When there is data in Child Tables

the Master tables cannot be deleted.

c) Business Integrity Rules :: The Third Intigrity rule is about the complex business

processes which cannot be implemented by the above 2 rules.

What are the Various Master and Detail Relation ships. The various Master and Detail Relationship are

a) NonIsolated :: The Master cannot be deleted when a child is exisiting

b) Isolated :: The Master can be deleted when the child is exisiting

c) Cascading :: The child gets deleted when the Master is deleted.

What are the Various Block Coordination Properties The various Block Coordination Properties are

a) Immediate Default Setting. The Detail records are shown when the Master Record

are shown.

b) Deffered with Auto Query Oracle Forms defer fetching the detail records until the

operator navigates to the detail block.

c) Deffered with No Auto Query The operator must navigate to the detail block and

explicitly execute a query

What are the Different Optimization Techniques The Various Optimisation techniques are

a) Execute Plan :: we can see the plan of the query and change it accordingly based on

the indexes

b) Optimizer_hint ::

set_item_property('DeptBlock',OPTIMIZER_HINT,'FIRST_ROWS');

Select /*+ First_Rows */ Deptno,Dname,Loc,Rowid from dept

where (Deptno > 25)

c) Optimize_Sql ::

By setting the Optimize_Sql = No, Oracle Forms assigns a single cursor for all SQL

statements.This slow downs the processing because for evertime the SQL must be

parsed whenver they are executed.

© Copyright : IT Engg Portal – www.itportal.in 445

f45run module = my_firstform userid = scott/tiger optimize_sql = No

d) Optimize_Tp ::

By setting the Optimize_Tp= No, Oracle Forms assigns seperate cursor only for each

query SELECT statement. All other SQL statements reuse the cursor.

f45run module = my_firstform userid = scott/tiger optimize_Tp = No

How does one change an Oracle user's password?(for DBA) Issue the following SQL command:

ALTER USER <username> IDENTIFIED BY <new_password>;

From Oracle8 you can just type "password" from SQL*Plus, or if you need to change

another user's password, type "password user_name". Look at this example:

SQL> password

Changing password for SCOTT

Old password:

New password:

Retype new password:

How does one create and drop database users? Look at these examples:

CREATE USER scott

IDENTIFIED BY tiger -- Assign password

DEFAULT TABLESACE tools -- Assign space for table and index segments

TEMPORARY TABLESPACE temp; -- Assign sort space

DROP USER scott CASCADE; -- Remove user

After creating a new user, assign the required privileges:

GRANT CONNECT, RESOURCE TO scott;

GRANT DBA TO scott; -- Make user a DB Administrator

Remember to give the user some space quota on its tablespaces:

ALTER USER scott QUOTA UNLIMITED ON tools;

Who created all these users in my database?/ Can I drop this user? (for DBA) Oracle creates a number of default database users or schemas when a new database is

created. Below are a few of them:

SYS/CHANGE_ON_INSTALL or INTERNAL

Oracle Data Dictionary/ Catalog

Created by: ?/rdbms/admin/sql.bsq and various cat*.sql scripts

Can password be changed: Yes (Do so right after the database was created)

© Copyright : IT Engg Portal – www.itportal.in 446

Can user be dropped: NO

SYSTEM/MANAGER

The default DBA user name (please do not use SYS)

Created by: ?/rdbms/admin/sql.bsq

Can password be changed: Yes (Do so right after the database was created)

Can user be dropped: NO

OUTLN/OUTLN

Stored outlines for optimizer plan stability

Created by: ?/rdbms/admin/sql.bsq

Can password be changed: Yes (Do so right after the database was created)

Can user be dropped: NO

SCOTT/TIGER, ADAMS/WOOD, JONES/STEEL, CLARK/CLOTH and

BLAKE/PAPER.

Training/ demonstration users containing the popular EMP and DEPT tables

Created by: ?/rdbms/admin/utlsampl.sql

Can password be changed: Yes

Can user be dropped: YES - Drop users cascade from all production environments

HR/HR (Human Resources), OE/OE (Order Entry), SH/SH (Sales History).

Training/ demonstration users containing the popular EMPLOYEES and

DEPARTMENTS tables

Created by: ?/demo/schema/mksample.sql

Can password be changed: Yes

Can user be dropped: YES - Drop users cascade from all production environments

CTXSYS/CTXSYS

Oracle interMedia (ConText Cartridge) administrator user

Created by: ?/ctx/admin/dr0csys.sql

TRACESVR/TRACE

Oracle Trace server

Created by: ?/rdbms/admin/otrcsvr.sql

DBSNMP/DBSNMP

Oracle Intelligent agent

Created by: ?/rdbms/admin/catsnmp.sql, called from catalog.sql

Can password be changed: Yes - put the new password in snmp_rw.ora file

Can user be dropped: YES - Only if you do not use the Intelligent Agents

ORDPLUGINS/ORDPLUGINS

Object Relational Data (ORD) User used by Time Series, etc.

Created by: ?/ord/admin/ordinst.sql

© Copyright : IT Engg Portal – www.itportal.in 447

ORDSYS/ORDSYS

Object Relational Data (ORD) User used by Time Series, etc

Created by: ?/ord/admin/ordinst.sql

DSSYS/DSSYS

Oracle Dynamic Services and Syndication Server

Created by: ?/ds/sql/dssys_init.sql

MDSYS/MDSYS

Oracle Spatial administrator user

Created by: ?/ord/admin/ordinst.sql

AURORA$ORB$UNAUTHENTICATED/INVALID

Used for users who do not authenticate in Aurora/ORB

Created by: ?/javavm/install/init_orb.sql called from ?/javavm/install/initjvm.sql

PERFSTAT/PERFSTAT

Oracle Statistics Package (STATSPACK) that supersedes UTLBSTAT/UTLESTAT

Created by: ?/rdbms/admin/statscre.sql

Remember to change the passwords for the SYS and SYSTEM users immediately

after installation!

Except for the user SYS, there should be no problem altering these users to use a

different default and temporary tablespace.

How does one enforce strict password control? (for DBA) By default Oracle's security is not extremely good. For example, Oracle will allow

users to choose single character passwords and passwords that match their names and

userids. Also, passwords don't ever expire. This means that one can hack an account

for years without ever locking the user.

From Oracle8 one can manage passwords through profiles. Some of the things that one

can restrict:

. FAILED_LOGIN_ATTEMPTS - failed login attempts before the account is locked

. PASSWORD_LIFE_TIME - limits the number of days the same password can be

used for authentication

. PASSWORD_REUSE_TIME - number of days before a password can be reused

. PASSWORD_REUSE_MAX - number of password changes required before the

current password can be reused

. PASSWORD_LOCK_TIME - number of days an account will be locked after

maximum failed login attempts

. PASSWORD_GRACE_TIME - number of days after the grace period begins during

which a warning is issued and login is allowed

© Copyright : IT Engg Portal – www.itportal.in 448

. PASSWORD_VERIFY_FUNCTION - password complexity verification script

Look at this simple example:

CREATE PROFILE my_profile LIMIT

PASSWORD_LIFE_TIME 30;

ALTER USER scott PROFILE my_profile;

How does one switch to another user in Oracle? (for DBA) Users normally use the "connect" statement to connect from one database user to

another. However, DBAs can switch from one user to another without a password. Of

course it is not advisable to bridge Oracle's security, but look at this example: SQL>

select password from dba_users where username='SCOTT';

PASSWORD

F894844C34402B67

SQL> alter user scott identified by lion;

User altered.

SQL> connect scott/lion

Connected.

REM Do whatever you like...

SQL> connect system/manager

Connected.

SQL> alter user scott identified by values 'F894844C34402B67';

User altered.

SQL> connect scott/tiger

Connected.

Note: Also see the su.sql script in the Useful Scripts and Sample Programs Page

What are snap shots and views

Snapshots are mirror or replicas of tables. Views are built using the columns from one

or more tables. The Single Table View can be updated but the view with multi table

cannot be updated

What are the OOPS concepts in Oracle. Oracle does implement the OOPS concepts. The best example is the Property Classes.

We can categorize the properties by setting the visual attributes and then attach the

© Copyright : IT Engg Portal – www.itportal.in 449

property classes for the objects. OOPS supports the concepts of objects and classes

and we can consider the property classes as classes and the items as objects

What is the difference between candidate key, unique key and primary key Candidate keys are the columns in the table that could be the primary keys and the

primary key is the key that has been selected to identify the rows. Unique key is also

useful for identifying the distinct rows in the table.)

What is concurrency Concurrency is allowing simultaneous access of same data by different users. Locks

useful for accesing the database are

a) Exclusive

The exclusive lock is useful for locking the row when an insert,update or delete is

being done.This lock should not be applied when we do only select from the row.

b) Share lock

We can do the table as Share_Lock as many share_locks can be put on the same

resource.

Previleges and Grants Previleges are the right to execute a particulare type of SQL statements. e.g :: Right to

Connect, Right to create, Right to resource Grants are given to the objects so that the

object might be accessed accordingly.The grant has to be given by the owner of the

object

Table Space,Data Files,Parameter File, Control Files Table Space :: The table space is useful for storing the data in the database.When a

database is created two table spaces are created.

a) System Table space :: This data file stores all the tables related to the system and

dba tables

b) User Table space :: This data file stores all the user related tables

We should have seperate table spaces for storing the tables and indexes so that the

access is fast.

Data Files :: Every Oracle Data Base has one or more physical data files.They store

the data for the database.Every datafile is associated with only one database.Once the

Data file is created the size cannot change.To increase the size of the database to store

more data we have to add data file.

Parameter Files :: Parameter file is needed to start an instance.A parameter file

contains the list of instance configuration parameters e.g.::

© Copyright : IT Engg Portal – www.itportal.in 450

db_block_buffers = 500

db_name = ORA7

db_domain = u.s.acme lang

Control Files :: Control files record the physical structure of the data files and redo log

files

They contain the Db name, name and location of dbs, data files ,redo log files and time

stamp.

Physical Storage of the Data The finest level of granularity of the data base are the data blocks.

Data Block :: One Data Block correspond to specific number of physical database

space

Extent :: Extent is the number of specific number of contigious data blocks.

Segments :: Set of Extents allocated for Extents. There are three types of Segments

a) Data Segment :: Non Clustered Table has data segment data of every table is stored

in cluster data segment

b) Index Segment :: Each Index has index segment that stores data

c) Roll Back Segment :: Temporarily store 'undo' information

What are the Pct Free and Pct Used Pct Free is used to denote the percentage of the free space that is to be left when

creating a table. Similarly Pct Used is used to denote the percentage of the used space

that is to be used when creating a table

eg.:: Pctfree 20, Pctused 40

What is Row Chaining The data of a row in a table may not be able to fit the same data block.Data for row is

stored in a chain of data blocks .

What is a 2 Phase Commit Two Phase commit is used in distributed data base systems. This is useful to maintain

the integrity of the database so that all the users see the same values. It contains DML

statements or Remote Procedural calls that reference a remote object. There are

basically 2 phases in a 2 phase commit.

a) Prepare Phase :: Global coordinator asks participants to prepare

b) Commit Phase :: Commit all participants to coordinator to Prepared, Read only or

abort Reply

© Copyright : IT Engg Portal – www.itportal.in 451

What is the difference between deleting and truncating of tables Deleting a table will not remove the rows from the table but entry is there in the

database dictionary and it can be retrieved But truncating a table deletes it completely

and it cannot be retrieved.

What are mutating tables When a table is in state of transition it is said to be mutating. eg :: If a row has been

deleted then the table is said to be mutating and no operations can be done on the table

except select.

What are Codd Rules Codd Rules describe the ideal nature of a RDBMS. No RDBMS satisfies all the 12

codd rules and Oracle Satisfies 11 of the 12 rules and is the only Rdbms to satisfy the

maximum number of rules.

What is Normalisation Normalisation is the process of organising the tables to remove the redundancy.There

are mainly 5 Normalisation rules.

a) 1 Normal Form :: A table is said to be in 1st Normal Form when the attributes are

atomic

b) 2 Normal Form :: A table is said to be in 2nd Normal Form when all the candidate

keys are dependant on the primary key

c) 3rd Normal Form :: A table is said to be third Normal form when it is not dependant

transitively

What is the Difference between a post query and a pre query A post query will fire for every row that is fetched but the pre query will fire only

once.

Deleting the Duplicate rows in the table We can delete the duplicate rows in the table by using the Rowid

Can U disable database trigger? How? Yes. With respect to table

ALTER TABLE TABLE

[[ DISABLE all_trigger ]]

© Copyright : IT Engg Portal – www.itportal.in 452

What is pseudo columns ? Name them? A pseudocolumn behaves like a table column, but is not actually stored in the table.

You can select from pseudocolumns, but you cannot insert, update, or delete their

values. This section describes these pseudocolumns:

* CURRVAL

* NEXTVAL

* LEVEL

* ROWID

* ROWNUM

How many columns can table have? The number of columns in a table can range from 1 to 254.

Is space acquired in blocks or extents ? In extents .

What is clustered index? In an indexed cluster, rows are stored together based on their cluster key values . Can

not applied for HASH.

What are the datatypes supported By oracle (INTERNAL)? Varchar2, Number,Char , MLSLABEL.

What are attributes of cursor? %FOUND , %NOTFOUND , %ISOPEN,%ROWCOUNT

Can you use select in FROM clause of SQL select ?

Yes.

Which trigger are created when master -detail relay?

master delete property

* NON-ISOLATED (default)

a) on check delete master

b) on clear details

c) on populate details

* ISOLATED

a) on clear details

b) on populate details

© Copyright : IT Engg Portal – www.itportal.in 453

* CASCADE

a) per-delete

b) on clear details

c) on populate details

which system variables can be set by users? SYSTEM.MESSAGE_LEVEL

SYSTEM.DATE_THRESHOLD

SYSTEM.EFFECTIVE_DATE

SYSTEM.SUPPRESS_WORKING

What are object group? An object group is a container for a group of objects. You define an object group when

you want to package related objects so you can copy or reference them in another

module.

What are referenced objects? Referencing allows you to create objects that inherit their functionality and appearance

from other objects. Referencing an object is similar to copying an object, except that

the resulting reference object maintains a link to its source object. A reference object

automatically inherits any changes that have been made to the source object when you

open or regenerate the module that contains the reference object.

Can you store objects in library? Referencing allows you to create objects that inherit their functionality and appearance

from other objects. Referencing an object is similar to copying an object, except that

the resulting reference object maintains a link to its source object. A reference object

automatically inherits any changes that have been made to the source object when you

open or regenerate the module that contains the reference object.

Is forms 4.5 object oriented tool ? why? yes , partially. 1) PROPERTY CLASS - inheritance property 2) OVERLOADING :

procedures and functions.

Can you issue DDL in forms? yes, but you have to use FORMS_DDL.

Referencing allows you to create objects that inherit their functionality and appearance

from other objects. Referencing an object is similar to copying an object, except that

© Copyright : IT Engg Portal – www.itportal.in 454

the resulting reference object maintains a link to its source object. A reference object

automatically inherits any changes that have been made to the source object when you

open or regenerate the module that contains the reference object. Any string

expression up to 32K:

- a literal

- an expression or a variable representing the text of a block of dynamically created

PL/SQL code

- a DML statement or

- a DDL statement

Restrictions:

The statement you pass to FORMS_DDL may not contain bind variable references in

the string, but the values of bind variables can be concatenated into the string before

passing the result to FORMS_DDL.

What is SECURE property? - Hides characters that the operator types into the text item. This setting is typically

used for password protection.

What are the types of triggers and how the sequence of firing in text item Triggers can be classified as Key Triggers, Mouse Triggers ,Navigational Triggers.

Key Triggers :: Key Triggers are fired as a result of Key action.e.g :: Key-next-field,

Key-up,Key-Down

Mouse Triggers :: Mouse Triggers are fired as a result of the mouse navigation.e.g.

When-mouse-button-presed,when-mouse-doubleclicked,etc

Navigational Triggers :: These Triggers are fired as a result of Navigation. E.g. : Post-

Text-item,Pre-text-item.

We also have event triggers like when ?new-form-instance and when-new-block-

instance.

We cannot call restricted procedures like go_to(?my_block.first_item?) in the

Navigational triggers

But can use them in the Key-next-item.

The Difference between Key-next and Post-Text is an very important question. The

key-next is fired as a result of the key action while the post text is fired as a result of

the mouse movement. Key next will not fire unless there is a key event. The sequence

of firing in a text item are as follows ::

a) pre - text

b) when new item

© Copyright : IT Engg Portal – www.itportal.in 455

c) key-next

d) when validate

e) post text

Can you store pictures in database? How? Yes , in long Raw datatype.

What are property classes ? Can property classes have trigger? Property class inheritance is a powerful feature that allows you to quickly define

objects that conform to your own interface and functionality standards. Property

classes also allow you to make global changes to applications quickly. By simply

changing the definition of a property class, you can change the definition of all objects

that inherit properties from that class.

Yes . All type of triggers .

If you have property class attached to an item and you have same trigger written

for the item . Which will fire first? Item level trigger fires , If item level trigger fires, property level trigger won't fire.

Triggers at the lowest level are always given the first preference. The item level

trigger fires first and then the block and then the Form level trigger.

What are record groups ? * Can record groups created at run-time? A record group is an internal Oracle Forms data structure that has a column/row

framework similar to a database table. However, unlike database tables, record groups

are separate objects that belong to the form module in which they are defined. A

record group can have an unlimited number of columns of type CHAR, LONG,

NUMBER, or DATE provided that the total number of columns does not exceed 64K.

Record group column names cannot exceed 30 characters.

Programmatically, record groups can be used whenever the functionality offered by a

two-dimensional array of multiple data types is desirable.

TYPES OF RECORD GROUP:

Query Record Group A query record group is a record group that has an associated

SELECT statement. The columns in a query record group derive their default names,

data types, and lengths from the database columns referenced in the SELECT

statement. The records in a query record group are the rows retrieved by the query

associated with that record group.

Non-query Record Group A non-query record group is a group that does not have an

associated query, but whose structure and values can be modified programmatically at

© Copyright : IT Engg Portal – www.itportal.in 456

runtime.

Static Record Group A static record group is not associated with a query; rather, you

define its structure and row values at design time, and they remain fixed at runtime.

What are ALERT? An ALERT is a modal window that displays a message notifying operator of some

application condition.

Can a button have icon and label at the same time ? -NO

What is mouse navigate property of button? When Mouse Navigate is True (the default), Oracle Forms performs standard

navigation to move the focus to the item when the operator activates the item with the

mouse.

When Mouse Navigate is set to False, Oracle Forms does not perform navigation (and

the resulting validation) to move to the item when an operator activates the item with

the mouse.

What is FORMS_MDI_WINDOW? forms run inside the MDI application window. This property is useful for calling a

form from another one.

What are timers ? when when-timer-expired does not fire? The When-Timer-Expired trigger can not fire during trigger, navigation, or transaction

processing.

Can object group have a block? Yes , object group can have block as well as program units.

How many types of canvases are there. There are 2 types of canvases called as Content and Stack Canvas. Content canvas is

the default and the one that is used mostly for giving the base effect. Its like a plate on

which we add items and stacked canvas is used for giving 3 dimensional effect.

What are user-exits? It invokes 3GL programs.

© Copyright : IT Engg Portal – www.itportal.in 457

Can you pass values to-and-fro from foreign function ? how ? Yes . You obtain a return value from a foreign function by assigning the return value

to an Oracle Forms variable or item. Make sure that the Oracle Forms variable or item

is the same data type as the return value from the foreign function.

After assigning an Oracle Forms variable or item value to a PL/SQL variable, pass the

PL/SQL variable as a parameter value in the PL/SQL interface of the foreign function.

The PL/SQL variable that is passed as a parameter must be a valid PL/SQL data type;

it must also be the appropriate parameter type as defined in the PL/SQL interface.

What is IAPXTB structure ? The entries of Pro * C and user exits and the form which simulate the proc or user_exit

are stored in IAPXTB table in d/b.

Can you call WIN-SDK thru user exits? YES.

Does user exits supports DLL on MSWINDOWS ?

YES .

What is path setting for DLL? Make sure you include the name of the DLL in the FORMS45_USEREXIT variable of

the ORACLE.INI file, or rename the DLL to F45XTB.DLL. If you rename the DLL to

F45XTB.DLL, replace the existing F45XTB.DLL in the ORAWINBIN directory with

the new F45XTB.DLL.

How is mapping of name of DLL and function done? The dll can be created using the Visual C++ / Visual Basic Tools and then the dll is

put in the path that is defined the registry.

What is precompiler? It is similar to C precompiler directives.

Can you connect to non - oracle datasource ? Yes .

What are key-mode and locking mode properties? level ? Key Mode : Specifies how oracle forms uniquely identifies rows in the database.This

is property includes for application that will run against NON-ORACLE datasources .

Key setting unique (default.)

© Copyright : IT Engg Portal – www.itportal.in 458

dateable

n-updateable.

Locking mode :

Specifies when Oracle Forms should attempt to obtain database locks on rows that

correspond to queried records in the form. a) immediate b) delayed

What are savepoint mode and cursor mode properties ? level? Specifies whether Oracle Forms should issue savepoints during a session. This

property is included primarily for applications that will run against non-ORACLE data

sources. For applications that will run against ORACLE, use the default setting.

Cursor mode - define cursor state across transaction Open/close.

What is transactional trigger property? Identifies a block as transactional control block. i.e. non - database block that oracle

forms should manage as transactional block.(NON-ORACLE datasource) default -

FALSE.

What is OLE automation ? OLE automation allows an OLE server application to expose a set of commands and

functions that can be invoked from an OLE container application. OLE automation

provides a way for an OLE container application to use the features of an OLE server

application to manipulate an OLE object from the OLE container environment.

(FORMS_OLE)

What does invoke built-in do? This procedure invokes a method.

Syntax:

PROCEDURE OLE2.INVOKE

(object obj_type,

method VARCHAR2,

list list_type := 0);

Parameters:

object Is an OLE2 Automation Object.

method Is a method (procedure) of the OLE2 object.

list Is the name of an argument list assigned to the OLE2.CREATE_ARGLIST

function.

© Copyright : IT Engg Portal – www.itportal.in 459

What are OPEN_FORM,CALL_FORM,NEW_FORM? diff? CALL_FORM : It calls the other form. but parent remains active, when called form

completes the operation , it releases lock and control goes back to the calling form.

When you call a form, Oracle Forms issues a savepoint for the called form. If the

CLEAR_FORM function causes a rollback when the called form is current, Oracle

Forms rolls back uncommitted changes to this savepoint.

OPEN_FORM : When you call a form, Oracle Forms issues a savepoint for the called

form. If the CLEAR_FORM function causes a rollback when the called form is

current, Oracle Forms rolls back uncommitted changes to this savepoint.

NEW_FORM : Exits the current form and enters the indicated form. The calling form

is terminated as the parent form. If the calling form had been called by a higher form,

Oracle Forms keeps the higher call active and treats it as a call to the new form. Oracle

Forms releases memory (such as database cursors) that the terminated form was

using.

Oracle Forms runs the new form with the same Runform options as the parent form. If

the parent form was a called form, Oracle Forms runs the new form with the same

options as the parent form.

What is call form stack? When successive forms are loaded via the CALL_FORM procedure, the resulting

module hierarchy is known as the call form stack.

Can u port applictions across the platforms? how? Yes we can port applications across platforms.Consider the form developed in a

windows system.The form would be generated in unix system by using f45gen

my_form.fmb scott/tiger

What is a visual attribute? Visual attributes are the font, color, and pattern properties that you set for form and

menu objects that appear in your application's interface.

Diff. between VAT and Property Class? Named visual attributes define only font, color, and pattern attributes; property classes

can contain these and any other properties.

You can change the appearance of objects at runtime by changing the named visual

attribute programmatically; property class assignment cannot be changed

programmatically. When an object is inheriting from both a property class and a

© Copyright : IT Engg Portal – www.itportal.in 460

named visual attribute, the named visual attribute settings take precedence, and any

visual attribute properties in the class are ignored.

Which trigger related to mouse? When-Mouse-Click

When-Mouse-DoubleClick

When-Mouse-Down

When-Mouse-Enter

When-Mouse-Leave

When-Mouse-Move

When-Mouse-Up

What is Current record attribute property? Specifies the named visual attribute used when an item is part of the current record.

Current Record Attribute is frequently used at the block level to display the current

row in a multi-record If you define an item-level Current Record Attribute, you can

display a pre-determined item in a special color when it is part of the current record,

but you cannot dynamically highlight the current item, as the input focus changes.

Can u change VAT at run time? Yes. You can programmatically change an object's named visual attribute setting to

change the font, color, and pattern of the object at runtime.

Can u set default font in forms? Yes. Change windows registry(regedit). Set form45_font to the desired font.

_break

What is Log Switch ? The point at which ORACLE ends writing to one online redo log file and begins

writing to another is called a log switch.

What is On-line Redo Log? The On-line Redo Log is a set of tow or more on-line redo files that record all

committed changes made to the database. Whenever a transaction is committed, the

corresponding redo entries temporarily stores in redo log buffers of the SGA are

written to an on-line redo log file by the background process LGWR. The on-line redo

log files are used in cyclical fashion.

© Copyright : IT Engg Portal – www.itportal.in 461

Which parameter specified in the DEFAULT STORAGE clause of CREATE

TABLESPACE cannot be altered after creating the tablespace? All the default storage parameters defined for the tablespace can be changed using the

ALTER TABLESPACE command. When objects are created their INITIAL and

MINEXTENS values cannot be changed.

What are the steps involved in Database Startup ? Start an instance, Mount the Database and Open the Database.

Rolling forward to recover data that has not been recorded in data files, yet has been

recorded in the on-line redo log, including the contents of rollback segments. Rolling

back transactions that have been explicitly rolled back or have not been committed as

indicated by the rollback segments regenerated in step a. Releasing any resources

(locks) held by transactions in process at the time of the failure. Resolving any

pending distributed transactions undergoing a two-phase commit at the time of the

instance failure.

Can Full Backup be performed when the database is open ? No.

What are the different modes of mounting a Database with the Parallel Server ? Exclusive Mode If the first instance that mounts a database does so in exclusive mode,

only that Instance can mount the database.

Parallel Mode If the first instance that mounts a database is started in parallel mode,

other instances that are started in parallel mode can also mount the database.

What are the advantages of operating a database in ARCHIVELOG mode over

operating it in NO ARCHIVELOG mode ? Complete database recovery from disk failure is possible only in ARCHIVELOG

mode. Online database backup is possible only in ARCHIVELOG mode.

What are the steps involved in Database Shutdown ? Close the Database, Dismount the Database and Shutdown the Instance.

What is Archived Redo Log ? Archived Redo Log consists of Redo Log files that have archived before being

reused.

© Copyright : IT Engg Portal – www.itportal.in 462

What is Restricted Mode of Instance Startup ? An instance can be started in (or later altered to be in) restricted mode so that when the

database is open connections are limited only to those whose user accounts have been

granted the RESTRICTED SESSION system privilege.

Can u have OLE objects in forms?

Yes.

Can u have VBX and OCX controls in forms ? Yes.

What r the types of windows (Window style)? Specifies whether the window is a Document window or a Dialog window.

What is OLE Activation style property? Specifies the event that will activate the OLE containing item.

Can u change the mouse pointer ? How? Yes. Specifies the mouse cursor style. Use this property to dynamically change the

shape of the cursor.

How many types of columns are there and what are they Formula columns :: For doing mathematical calculations and returning one value

Summary Columns :: For doing summary calculations such as summations etc. Place

holder Columns :: These columns are useful for storing the value in a variable

Can u have more than one layout in report It is possible to have more than one layout in a report by using the additional layout

option in the layout editor.

Can u run the report with out a parameter form Yes it is possible to run the report without parameter form by setting the PARAM

value to Null

What is the lock option in reports layout By using the lock option we cannot move the fields in the layout editor outside the

frame. This is useful for maintaining the fields .

© Copyright : IT Engg Portal – www.itportal.in 463

What is Flex Flex is the property of moving the related fields together by setting the flex property

on

What are the minimum number of groups required for a matrix report The minimum of groups required for a matrix report are 4 e -----

What is a Synonym ? A synonym is an alias for a table, view, sequence or program unit.

What is a Sequence ? A sequence generates a serial list of unique numbers for numerical columns of a

database's tables.

What is a Segment ? A segment is a set of extents allocated for a certain logical structure.

What is schema? A schema is collection of database objects of a User.

Describe Referential Integrity ? A rule defined on a column (or set of columns) in one table that allows the insert or

update of a row only if the value for the column or set of columns (the dependent

value) matches a value in a column of a related table (the referenced value). It also

specifies the type of data manipulation allowed on referenced data and the action to be

performed on dependent data as a result of any action on referenced data.

What is Hash Cluster ? A row is stored in a hash cluster based on the result of applying a hash function to the

row's cluster key value. All rows with the same hash key value are stores together on

disk.

What is a Private Synonyms ? A Private Synonyms can be accessed only by the owner.

What is Database Link ? A database link is a named object that describes a "path" from one database to another.

© Copyright : IT Engg Portal – www.itportal.in 464

What is index cluster? A cluster with an index on the cluster key.

What is hash cluster? A row is stored in a hash cluster based on the result of applying a hash function to the

row's cluster key value. All rows with the same hash key value are stores together on

disk.

When can hash cluster used? Hash clusters are better choice when a table is often queried with equality queries. For

such queries the specified cluster key value is hashed. The resulting hash key value

points directly to the area on disk that stores the specified rows.

When can hash cluster used? Hash clusters are better choice when a table is often queried with equality queries. For

such queries the specified cluster key value is hashed. The resulting hash key value

points directly to the area on disk that stores the specified rows.

What are the types of database links? Private database link, public database link & network database link.

What is private database link? Private database link is created on behalf of a specific user. A private database link can

be used only when the owner of the link specifies a global object name in a SQL

statement or in the definition of the owner's views or procedures.

What is public database link? Public database link is created for the special user group PUBLIC. A public database

link can be used when any user in the associated database specifies a global object

name in a SQL statement or object definition.

What is network database link? Network database link is created and managed by a network domain service. A

network database link can be used when any user of any database in the network

specifies a global object name in a SQL statement or object definition.

What is data block? Oracle database's data is stored in data blocks. One data block corresponds to a

specific number of bytes of physical database space on disk.

© Copyright : IT Engg Portal – www.itportal.in 465

How to define data block size? A data block size is specified for each Oracle database when the database is created. A

database users and allocated free database space in Oracle data blocks. Block size is

specified in init.ora file and cannot be changed latter.

What is row chaining? In circumstances, all of the data for a row in a table may not be able to fit in the same

data block. When this occurs, the data for the row is stored in a chain of data block

(one or more) reserved for that segment.

What is an extent? An extent is a specific number of contiguous data blocks, obtained in a single

allocation and used to store a specific type of information.

What are the different types of segments?

Data segment, index segment, rollback segment and temporary segment.

What is a data segment? Each non-clustered table has a data segment. All of the table's data is stored in the

extents of its data segment. Each cluster has a data segment. The data of every table in

the cluster is stored in the cluster's data segment.

What is an index segment? Each index has an index segment that stores all of its data.

What is rollback segment? A database contains one or more rollback segments to temporarily store "undo"

information.

What are the uses of rollback segment? To generate read-consistent database information during database recovery and to

rollback uncommitted transactions by the users.

What is a temporary segment? Temporary segments are created by Oracle when a SQL statement needs a temporary

work area to complete execution. When the statement finishes execution, the

temporary segment extents are released to the system for future use.

© Copyright : IT Engg Portal – www.itportal.in 466

What is a datafile? Every Oracle database has one or more physical data files. A database's data files

contain all the database data. The data of logical database structures such as tables and

indexes is physically stored in the data files allocated for a database.

What are the characteristics of data files? A data file can be associated with only one database. Once created a data file can't

change size. One or more data files form a logical unit of database storage called a

tablespace.

What is a redo log? The set of redo log files for a database is collectively known as the database redo log.

What is the function of redo log? The primary function of the redo log is to record all changes made to data.

What is the use of redo log information? The information in a redo log file is used only to recover the database from a system

or media failure prevents database data from being written to a database's data files.

What does a control file contains? - Database name

- Names and locations of a database's files and redolog files.

- Time stamp of database creation.

What is the use of control file? When an instance of an Oracle database is started, its control file is used to identify the

database and redo log files that must be opened for database operation to proceed. It is

also used in database recovery.

Is it possible to split the print reviewer into more than one region? Yes

Is it possible to center an object horizontally in a repeating frame that has a

variable horizontal size?

Yes

© Copyright : IT Engg Portal – www.itportal.in 467

For a field in a repeating frame, can the source come from the column which does

not exist in the data group which forms the base for the frame? Yes

Can a field be used in a report without it appearing in any data group? Yes

The join defined by the default data link is an outer join yes or no?

Yes

Can a formula column referred to columns in higher group? Yes

Can a formula column be obtained through a select statement? Yes

Is it possible to insert comments into sql statements return in the data model

editor? Yes

Is it possible to disable the parameter from while running the report? Yes

When a form is invoked with call_form, Does oracle forms issues a save point? Yes

Explain the difference between a hot backup and a cold backup and the benefits

associated with each. A hot backup is basically taking a backup of the database while it is still up and

running and it must be in archive log mode. A cold backup is taking a backup of the

database while it is shut down and does not require being in archive log mode. The

benefit of taking a hot backup is that the database is still available for use while the

backup is occurring and you can recover the database to any point in time. The benefit

of taking a cold backup is that it is typically easier to administer the backup and

recovery process. In addition, since you are taking cold backups the database does not

require being in archive log mode and thus there will be a slight performance gain as

the database is not cutting archive logs to disk.

© Copyright : IT Engg Portal – www.itportal.in 468

You have just had to restore from backup and do not have any control files. How

would you go about bringing up this database? I would create a text based backup control file, stipulating where on disk all the data

files where and then issue the recover command with the using backup control file

clause.

How do you switch from an init.ora file to a spfile? Issue the create spfile from pfile command.

Explain the difference between a data block, an extent and a segment. A data block is the smallest unit of logical storage for a database object. As objects

grow they take chunks of additional storage that are composed of contiguous data

blocks. These groupings of contiguous data blocks are called extents. All the extents

that an object takes when grouped together are considered the segment of the database

object.

Give two examples of how you might determine the structure of the table DEPT. Use the describe command or use the dbms_metadata.get_ddl package.

Where would you look for errors from the database engine? In the alert log.

Compare and contrast TRUNCATE and DELETE for a table.

Both the truncate and delete command have the desired outcome of getting rid of all

the rows in a table. The difference between the two is that the truncate command is a

DDL operation and just moves the high water mark and produces a now rollback. The

delete command, on the other hand, is a DML operation, which will produce a

rollback and thus take longer to complete.

Give the reasoning behind using an index. Faster access to data blocks in a table.

Give the two types of tables involved in producing a star schema and the type of

data they hold. Fact tables and dimension tables. A fact table contains measurements while dimension

tables will contain data that will help describe the fact tables.

What type of index should you use on a fact table? A Bitmap index.

© Copyright : IT Engg Portal – www.itportal.in 469

Give two examples of referential integrity constraints. A primary key and a foreign key.

A table is classified as a parent table and you want to drop and re-create it. How

would you do this without affecting the children tables? Disable the foreign key constraint to the parent, drop the table, re-create the table,

enable the foreign key constraint.

Explain the difference between ARCHIVELOG mode and NOARCHIVELOG

mode and the benefits and disadvantages to each. ARCHIVELOG mode is a mode that you can put the database in for creating a backup

of all transactions that have occurred in the database so that you can recover to any

point in time. NOARCHIVELOG mode is basically the absence of ARCHIVELOG

mode and has the disadvantage of not being able to recover to any point in time.

NOARCHIVELOG mode does have the advantage of not having to write transactions

to an archive log and thus increases the performance of the database slightly.

What command would you use to create a backup control file?

Alter database backup control file to trace.

Give the stages of instance startup to a usable state where normal users may

access it. STARTUP NOMOUNT - Instance startup

STARTUP MOUNT - The database is mounted

STARTUP OPEN - The database is opened

What column differentiates the V$ views to the GV$ views and how? The INST_ID column which indicates the instance in a RAC environment the

information came from.

How would you go about generating an EXPLAIN plan? Create a plan table with utlxplan.sql.

Use the explain plan set statement_id = 'tst1' into plan_table for a SQL statement

Look at the explain plan with utlxplp.sql or utlxpls.sql

How would you go about increasing the buffer cache hit ratio? Use the buffer cache advisory over a given workload and then query the

© Copyright : IT Engg Portal – www.itportal.in 470

v$db_cache_advice table. If a change was necessary then I would use the alter system

set db_cache_size command.

Explain an ORA-01555 You get this error when you get a snapshot too old within rollback. It can usually be

solved by increasing the undo retention or increasing the size of rollbacks. You should

also look at the logic involved in the application getting the error message.

Explain the difference between $ORACLE_HOME and $ORACLE_BASE. ORACLE_BASE is the root directory for oracle. ORACLE_HOME located beneath

ORACLE_BASE is where the oracle products reside.

How would you determine the time zone under which a database was operating? select DBTIMEZONE from dual;

Explain the use of setting GLOBAL_NAMES equal to TRUE. Setting GLOBAL_NAMES dictates how you might connect to a database. This

variable is either TRUE or FALSE and if it is set to TRUE it enforces database links to

have the same name as the remote database to which they are linking.

What command would you use to encrypt a PL/SQL application? WRAP

Explain the difference between a FUNCTION, PROCEDURE and PACKAGE. A function and procedure are the same in that they are intended to be a collection of

PL/SQL code that carries a single task. While a procedure does not have to return any

values to the calling application, a function will return a single value. A package on

the other hand is a collection of functions and procedures that are grouped together

based on their commonality to a business function or application.

Explain the use of table functions. Table functions are designed to return a set of rows through PL/SQL logic but are

intended to be used as a normal table or view in a SQL statement. They are also used

to pipeline information in an ETL process.

Name three advisory statistics you can collect. Buffer Cache Advice, Segment Level Statistics, & Timed Statistics

© Copyright : IT Engg Portal – www.itportal.in 471

Where in the Oracle directory tree structure are audit traces placed? In unix $ORACLE_HOME/rdbms/audit, in Windows the event viewer

Explain materialized views and how they are used. Materialized views are objects that are reduced sets of information that have been

summarized, grouped, or aggregated from base tables. They are typically used in data

warehouse or decision support systems.

When a user process fails, what background process cleans up after it? PMON

What background process refreshes materialized views? The Job Queue Processes.

How would you determine what sessions are connected and what resources they

are waiting for? Use of V$SESSION and V$SESSION_WAIT

Describe what redo logs are. Redo logs are logical and physical structures that are designed to hold all the changes

made to a database and are intended to aid in the recovery of a database.

How would you force a log switch? ALTER SYSTEM SWITCH LOGFILE;

Give two methods you could use to determine what DDL changes have been

made. You could use Logminer or Streams

What does coalescing a tablespace do? Coalescing is only valid for dictionary-managed tablespaces and de-fragments space

by combining neighboring free extents into large single extents.

What is the difference between a TEMPORARY tablespace and a PERMANENT

tablespace? A temporary tablespace is used for temporary objects such as sort structures while

permanent tablespaces are used to store those objects meant to be used as the true

objects of the database.

© Copyright : IT Engg Portal – www.itportal.in 472

Name a tablespace automatically created when you create a database. The SYSTEM tablespace.

When creating a user, what permissions must you grant to allow them to connect

to the database? Grant the CONNECT to the user.

How do you add a data file to a tablespace ALTER TABLESPACE <tablespace_name> ADD DATAFILE <datafile_name>

SIZE

How do you resize a data file? ALTER DATABASE DATAFILE <datafile_name> RESIZE <new_size>;

What view would you use to look at the size of a data file? DBA_DATA_FILES

What view would you use to determine free space in a tablespace? DBA_FREE_SPACE

How would you determine who has added a row to a table? Turn on fine grain auditing for the table.

How can you rebuild an index? ALTER INDEX <index_name> REBUILD;

Explain what partitioning is and what its benefit is. Partitioning is a method of taking large tables and indexes and splitting them into

smaller, more manageable pieces.

You have just compiled a PL/SQL package but got errors, how would you view

the errors? SHOW ERRORS

How can you gather statistics on a table? The ANALYZE command.

© Copyright : IT Engg Portal – www.itportal.in 473

How can you enable a trace for a session? Use the DBMS_SESSION.SET_SQL_TRACE or

Use ALTER SESSION SET SQL_TRACE = TRUE;

What is the difference between the SQL*Loader and IMPORT utilities? These two Oracle utilities are used for loading data into the database. The difference is

that the import utility relies on the data being produced by another Oracle utility

EXPORT while the SQL*Loader utility allows data to be loaded that has been

produced by other utilities from different data sources just so long as it conforms to

ASCII formatted or delimited files.

Name two files used for network connection to a database. TNSNAMES.ORA and SQLNET.ORA

What is the function of Optimizer ?

The goal of the optimizer is to choose the most efficient way to execute a SQL

statement.

What is Execution Plan ? The combinations of the steps the optimizer chooses to execute a statement is called an

execution plan.

Can one resize tablespaces and data files? (for DBA) One can manually increase or decrease the size of a datafile from Oracle 7.2 using the

command.

ALTER DATABASE DATAFILE 'filename2' RESIZE 100M;

Because you can change the sizes of datafiles, you can add more space to your

database without adding more datafiles. This is beneficial if you are concerned about

reaching the maximum number of datafiles allowed in your database.

Manually reducing the sizes of datafiles allows you to reclaim unused space in the

database. This is useful for correcting errors in estimations of space requirements.

Also, datafiles can be allowed to automatically extend if more space is required. Look

at the following command:

CREATE TABLESPACE pcs_data_ts

DATAFILE 'c:\ora_apps\pcs\pcsdata1.dbf' SIZE 3M

AUTOEXTEND ON NEXT 1M MAXSIZE UNLIMITED

DEFAULT STORAGE (INITIAL 10240

NEXT 10240

© Copyright : IT Engg Portal – www.itportal.in 474

MINEXTENTS 1

MAXEXTENTS UNLIMITED

PCTINCREASE 0)

ONLINE

PERMANENT;

What is SAVE POINT ? For long transactions that contain many SQL statements, intermediate markers or

savepoints can be declared which can be used to divide a transaction into smaller

parts. This allows the option of later rolling back all work performed from the current

point in the transaction to a declared savepoint within the transaction.

What are the values that can be specified for OPTIMIZER MODE Parameter ? COST and RULE.

Can one rename a tablespace? (for DBA) No, this is listed as Enhancement Request 148742. Workaround:

Export all of the objects from the tablespace

Drop the tablespace including contents

Recreate the tablespace

Import the objects

What is RULE-based approach to optimization ? Choosing an executing planbased on the access paths available and the ranks of these

access paths.

What are the values that can be specified for OPTIMIZER_GOAL parameter of

the ALTER SESSION Command ? CHOOSE,ALL_ROWS,FIRST_ROWS and RULE.

How does one create a standby database? (for DBA) While your production database is running, take an (image copy) backup and restore it

on duplicate hardware. Note that an export will not work!!!

On your standby database, issue the following commands:

ALTER DATABASE CREATE STANDBY CONTROLFILE AS 'filename';

ALTER DATABASE MOUNT STANDBY DATABASE;

RECOVER STANDBY DATABASE;

On systems prior to Oracle 8i, write a job to copy archived redo log files from the

© Copyright : IT Engg Portal – www.itportal.in 475

primary database to the standby system, and apply the redo log files to the standby

database (pipe it). Remember the database is recovering and will prompt you for the

next log file to apply.

Oracle 8i onwards provide an "Automated Standby Database" feature, which will send

archived, log files to the remote site via NET8, and apply then to the standby

database.

When one needs to activate the standby database, stop the recovery process and

activate it:

ALTER DATABASE ACTIVATE STANDBY DATABASE;

How does one give developers access to trace files (required as input to tkprof)?

(for DBA) The "alter session set sql_trace=true" command generates trace files in

USER_DUMP_DEST that can be used by developers as input to tkprof. On Unix the

default file mask for these files are "rwx r-- ---".

There is an undocumented INIT.ORA parameter that will allow everyone to read (rwx

r-r--) these trace files:

_trace_files_public = true

Include this in your INIT.ORA file and bounce your database for it to take effect.

What are the responsibilities of a Database Administrator ? Installing and upgrading the Oracle Server and application tools. Allocating system

storage and planning future storage requirements for the database system. Managing

primary database structures (tablespaces) Managing primary objects

(table,views,indexes) Enrolling users and maintaining system security. Ensuring

compliance with Oralce license agreement Controlling and monitoring user access to

the database. Monitoring and optimizing the performance of the database. Planning for

backup and recovery of database information. Maintain archived data on tape Backing

up and restoring the database. Contacting Oracle Corporation for technical support.

What is a trace file and how is it created ? Each server and background process can write an associated trace file. When an

internal error is detected by a process or user process, it dumps information about the

error to its trace. This can be used for tuning the database.

What are the roles and user accounts created automatically with the database? DBA - role Contains all database system privileges.

SYS user account - The DBA role will be assigned to this account. All of the base

© Copyright : IT Engg Portal – www.itportal.in 476

tables and views for the database's dictionary are store in this schema and are

manipulated only by ORACLE. SYSTEM user account - It has all the system

privileges for the database and additional tables and views that display administrative

information and internal tables and views used by oracle tools are created using this

username.

What are the minimum parameters should exist in the parameter file (init.ora) ? DB NAME - Must set to a text string of no more than 8 characters and it will be stored

inside the datafiles, redo log files and control files and control file while database

creation.

DB_DOMAIN - It is string that specifies the network domain where the database is

created. The global database name is identified by setting these parameters

(DB_NAME & DB_DOMAIN) CONTORL FILES - List of control filenames of the

database. If name is not mentioned then default name will be used.

DB_BLOCK_BUFFERS - To determine the no of buffers in the buffer cache in SGA.

PROCESSES - To determine number of operating system processes that can be

connected to ORACLE concurrently. The value should be 5 (background process) and

additional 1 for each user.

ROLLBACK_SEGMENTS - List of rollback segments an ORACLE instance acquires

at database startup. Also optionally

LICENSE_MAX_SESSIONS,LICENSE_SESSION_WARNING and

LICENSE_MAX_USERS.

Why and when should I backup my database? (for DBA) Backup and recovery is one of the most important aspects of a DBAs job. If you lose

your company's data, you could very well lose your job. Hardware and software can

always be replaced, but your data may be irreplaceable!

Normally one would schedule a hierarchy of daily, weekly and monthly backups,

however consult with your users before deciding on a backup schedule. Backup

frequency normally depends on the following factors:

. Rate of data change/ transaction rate

. Database availability/ Can you shutdown for cold backups?

. Criticality of the data/ Value of the data to the company

. Read-only tablespace needs backing up just once right after you make it read-only

. If you are running in archivelog mode you can backup parts of a database over an

extended cycle of days

. If archive logging is enabled one needs to backup archived log files timeously to

© Copyright : IT Engg Portal – www.itportal.in 477

prevent database freezes

. Etc.

Carefully plan backup retention periods. Ensure enough backup media (tapes) are

available and that old backups are expired in-time to make media available for new

backups. Off-site vaulting is also highly recommended.

Frequently test your ability to recover and document all possible scenarios.

Remember, it's the little things that will get you. Most failed recoveries are a result of

organizational errors and miscommunications.

What strategies are available for backing-up an Oracle database? (for DBA) The following methods are valid for backing-up an Oracle database:

Export/Import - Exports are "logical" database backups in that they extract logical

definitions and data from the database to a file.

Cold or Off-line Backups - Shut the database down and backup up ALL data, log, and

control files.

Hot or On-line Backups - If the databases are available and in ARCHIVELOG mode,

set the tablespaces into backup mode and backup their files. Also remember to backup

the control files and archived redo log files.

RMAN Backups - While the database is off-line or on-line, use the "rman" utility to

backup the database.

It is advisable to use more than one of these methods to backup your database. For

example, if you choose to do on-line database backups, also cover yourself by doing

database exports. Also test ALL backup and recovery scenarios carefully. It is better to

be save than sorry.

Regardless of your strategy, also remember to backup all required software libraries,

parameter files, password files, etc. If your database is in ARCGIVELOG mode, you

also need to backup archived log files.

What is the difference between online and offline backups? (for DBA) A hot backup is a backup performed while the database is online and available for

read/write. Except for Oracle exports, one can only do on-line backups when running

in ARCHIVELOG mode.

A cold backup is a backup performed while the database is off-line and unavailable to

its users.

What is the difference between restoring and recovering? (for DBA) Restoring involves copying backup files from secondary storage (backup media) to

© Copyright : IT Engg Portal – www.itportal.in 478

disk. This can be done to replace damaged files or to copy/move a database to a new

location.

Recovery is the process of applying redo logs to the database to roll it forward. One

can roll-forward until a specific point-in-time (before the disaster occurred), or roll-

forward until the last transaction recorded in the log files. Sql> connect SYS as

SYSDBA

Sql> RECOVER DATABASE UNTIL TIME '2001-03-06:16:00:00' USING

BACKUP CONTROLFILE;

How does one backup a database using the export utility? (for DBA) Oracle exports are "logical" database backups (not physical) as they extract data and

logical definitions from the database into a file. Other backup strategies normally

back-up the physical data files.

One of the advantages of exports is that one can selectively re-import tables, however

one cannot roll-forward from an restored export file. To completely restore a database

from an export file one practically needs to recreate the entire database.

Always do full system level exports (FULL=YES). Full exports include more

information about the database in the export file than user level exports.

What are the built_ins used the display the LOV? Show_lov

List_values

How do you call other Oracle Products from Oracle Forms? Run_product is a built-in, Used to invoke one of the supported oracle tools products

and specifies the name of the document or module to be run. If the called product is

unavailable at the time of the call, Oracle Forms returns a message to the operator.

What is the main diff. bet. Reports 2.0 & Reports 2.5? Report 2.5 is object oriented.

What are the Built-ins to display the user-named editor? A user named editor can be displayed programmatically with the built in procedure

SHOW-EDITOR, EDIT_TETITEM independent of any particular text item.

How many number of columns a record group can have? A record group can have an unlimited number of columns of type CHAR, LONG,

NUMBER, or DATE provided that the total number of column does not exceed 64K.

© Copyright : IT Engg Portal – www.itportal.in 479

What is a Query Record Group? A query record group is a record group that has an associated SELECT statement. The

columns in a query record group derive their default names, data types, had lengths

from the database columns referenced in the SELECT statement. The records in query

record group are the rows retrieved by the query associated with that record group.

What does the term panel refer to with regard to pages? A panel is the no. of physical pages needed to print one logical page.

What is a master detail relationship? A master detail relationship is an association between two base table blocks- a master

block and a detail block. The relationship between the blocks reflects a primary key to

foreign key relationship between the tables on which the blocks are based.

What is a library? A library is a collection of subprograms including user named procedures, functions

and packages.

What is an anchoring object & what is its use? What are the various sub events a

mouse double click event involves?

An anchoring object is a print condition object which used to explicitly or implicitly

anchor other objects to itself.

Use the add_group_column function to add a column to record group that was

created at a design time? False

What are the various sub events a mouse double click event involves? What are

the various sub events a mouse double click event involves? Double clicking the mouse consists of the mouse down, mouse up, mouse click, mouse

down & mouse up events.

What is the use of break group? What are the various sub events a mouse double

click event involves?

A break group is used to display one record for one group ones. While multiple related

records in other group can be displayed.

What tuning indicators can one use? (for DBA) The following high-level tuning indicators can be used to establish if a database is

© Copyright : IT Engg Portal – www.itportal.in 480

performing optimally or not:

. Buffer Cache Hit Ratio

Formula: Hit Ratio = (Logical Reads - Physical Reads) / Logical Reads

Action: Increase DB_CACHE_SIZE (DB_BLOCK_BUFFERS prior to 9i) to increase

hit ratio

. Library Cache Hit Ratio

Action: Increase the SHARED_POOL_SIZE to increase hit ratio

What tools/utilities does Oracle provide to assist with performance tuning? (for

DBA) Oracle provide the following tools/ utilities to assist with performance monitoring and

tuning:

. TKProf

. UTLBSTAT.SQL and UTLESTAT.SQL - Begin and end stats monitoring

. Statspack

. Oracle Enterprise Manager - Tuning Pack

What is STATSPACK and how does one use it? (for DBA) Statspack is a set of performance monitoring and reporting utilities provided by Oracle

from Oracle8i and above. Statspack provides improved BSTAT/ESTAT functionality,

though the old BSTAT/ESTAT scripts are still available. For more information about

STATSPACK, read the documentation in file

$ORACLE_HOME/rdbms/admin/spdoc.txt.

Install Statspack:

cd $ORACLE_HOME/rdbms/admin

sqlplus "/ as sysdba" @spdrop.sql -- Install Statspack -

sqlplus "/ as sysdba" @spcreate.sql-- Enter tablespace names when prompted

Use Statspack:

sqlplus perfstat/perfstat

exec statspack.snap; -- Take a performance snapshots

exec statspack.snap;

o Get a list of snapshots

select SNAP_ID, SNAP_TIME from STATS$SNAPSHOT;

@spreport.sql -- Enter two snapshot id's for difference report

Other Statspack Scripts:

. sppurge.sql - Purge a range of Snapshot Id's between the specified begin and end

Snap Id's

© Copyright : IT Engg Portal – www.itportal.in 481

. spauto.sql - Schedule a dbms_job to automate the collection of STATPACK

statistics

. spcreate.sql - Installs the STATSPACK user, tables and package on a database (Run

as SYS).

. spdrop.sql - Deinstall STATSPACK from database (Run as SYS)

. sppurge.sql - Delete a range of Snapshot Id's from the database

. spreport.sql - Report on differences between values recorded in two snapshots

. sptrunc.sql - Truncates all data in Statspack tables

What are the common RMAN errors (with solutions)? (for DBA) Some of the common RMAN errors are:

RMAN-20242: Specification does not match any archivelog in the recovery catalog.

Add to RMAN script: sql 'alter system archive log current';

RMAN-06089: archived log xyz not found or out of sync with catalog

Execute from RMAN: change archivelog all validate;

How can you execute the user defined triggers in forms 3.0 ? Execute Trigger (trigger-name)

What ERASE package procedure does ? Erase removes an indicated global variable.

What is the difference between NAME_IN and COPY ? Copy is package procedure and writes values into a field.

Name in is a package function and returns the contents of the variable to which you

apply.

What package procedure is used for calling another form ? Call (E.g. Call(formname)

When the form is running in DEBUG mode, If you want to examine the values of

global variables and other form variables, What package procedure command

you would use in your trigger text ? Break.

SYSTEM VARIABLES

The value recorded in system.last_record variable is of type

a. Number

© Copyright : IT Engg Portal – www.itportal.in 482

b. Boolean

c. Character. ? b. Boolean.

What is mean by Program Global Area (PGA) ? It is area in memory that is used by a Single Oracle User Process.

What is hit ratio ? It is a measure of well the data cache buffer is handling requests for data. Hit Ratio =

(Logical Reads - Physical Reads - Hits Misses)/ Logical Reads.

How do u implement the If statement in the Select Statement We can implement the if statement in the select statement by using the Decode

statement. e.g. select DECODE (EMP_CAT,'1','First','2','Second'Null); Here the Null

is the else statement where null is done .

How many types of Exceptions are there There are 2 types of exceptions. They are

a) System Exceptions

e.g. When no_data_found, When too_many_rows

b) User Defined Exceptions

e.g. My_exception exception

When My_exception then

What are the inline and the precompiler directives The inline and precompiler directives detect the values directly

How do you use the same lov for 2 columns We can use the same lov for 2 columns by passing the return values in global values

and using the global values in the code

How many minimum groups are required for a matrix report The minimum number of groups in matrix report are 4

What is the difference between static and dynamic lov The static lov contains the predetermined values while the dynamic lov contains

values that come at run time

© Copyright : IT Engg Portal – www.itportal.in 483

How does one manage Oracle database users? (for DBA) Oracle user accounts can be locked, unlocked, forced to choose new passwords, etc.

For example, all accounts except SYS and SYSTEM will be locked after creating an

Oracle9iDB database using the DB Configuration Assistant (dbca). DBA's must

unlock these accounts to make them available to users.

Look at these examples:

ALTER USER scott ACCOUNT LOCK -- lock a user account

ALTER USER scott ACCOUNT UNLOCK; -- unlocks a locked users account

ALTER USER scott PASSWORD EXPIRE; -- Force user to choose a new password

What is the difference between DBFile Sequential and Scattered Reads?(for

DBA) Both "db file sequential read" and "db file scattered read" events signify time waited

for I/O read requests to complete. Time is reported in 100's of a second for Oracle 8i

releases and below, and 1000's of a second for Oracle 9i and above. Most people

confuse these events with each other as they think of how data is read from disk.

Instead they should think of how data is read into the SGA buffer cache.

db file sequential read:

A sequential read operation reads data into contiguous memory (usually a single-block

read with p3=1, but can be multiple blocks). Single block I/Os are usually the result of

using indexes. This event is also used for rebuilding the control file and reading data

file headers (P2=1). In general, this event is indicative of disk contention on index

reads.

db file scattered read:

Similar to db file sequential reads, except that the session is reading multiple data

blocks and scatters them into different discontinuous buffers in the SGA. This statistic

is NORMALLY indicating disk contention on full table scans. Rarely, data from full

table scans could be fitted into a contiguous buffer area, these waits would then show

up as sequential reads instead of scattered reads.

The following query shows average wait time for sequential versus scattered reads:

prompt "AVERAGE WAIT TIME FOR READ REQUESTS"

select a.average_wait "SEQ READ", b.average_wait "SCAT READ"

from sys.v_$system_event a, sys.v_$system_event b

where a.event = 'db file sequential read'

and b.event = 'db file scattered read';

© Copyright : IT Engg Portal – www.itportal.in 484

What is the use of PARFILE option in EXP command ? Name of the parameter file to be passed for export.

What is the use of TABLES option in EXP command ? List of tables should be exported.ze)

What is the OPTIMAL parameter? It is used to set the optimal length of a rollback segment.

How does one use ORADEBUG from Server Manager/ SQL*Plus? (for DBA) Execute the "ORADEBUG HELP" command from svrmgrl or sqlplus to obtain a list

of valid ORADEBUG commands. Look at these examples:

SQLPLUS> REM Trace SQL statements with bind variables

SQLPLUS> oradebug setospid 10121

Oracle pid: 91, Unix process pid: 10121, image: oracleorcl

SQLPLUS> oradebug EVENT 10046 trace name context forever, level 12

Statement processed.

SQLPLUS> ! vi /app/oracle/admin/orcl/bdump/ora_10121.trc

SQLPLUS> REM Trace Process Statistics

SQLPLUS> oradebug setorapid 2

Unix process pid: 1436, image: ora_pmon_orcl

SQLPLUS> oradebug procstat

Statement processed.

SQLPLUS>> oradebug TRACEFILE_NAME

/app/oracle/admin/orcl/bdump/pmon_1436.trc

SQLPLUS> REM List semaphores and shared memory segments in use

SQLPLUS> oradebug ipc

SQLPLUS> REM Dump Error Stack

SQLPLUS> oradebug setospid <pid>

SQLPLUS> oradebug event immediate trace name errorstack level 3

SQLPLUS> REM Dump Parallel Server DLM locks

SQLPLUS> oradebug lkdebug -a convlock

SQLPLUS> oradebug lkdebug -a convres

SQLPLUS> oradebug lkdebug -r <resource handle> (i.e 0x8066d338 from convres

dump)

Are there any undocumented commands in Oracle? (for DBA) Sure there are, but it is hard to find them. Look at these examples:

© Copyright : IT Engg Portal – www.itportal.in 485

From Server Manager (Oracle7.3 and above): ORADEBUG HELP

It looks like one can change memory locations with the ORADEBUG POKE

command. Anyone brave enough to test this one for us? Previously this functionality

was available with ORADBX (ls -l $ORACLE_HOME/rdbms/lib/oradbx.o; make -f

oracle.mk oradbx) SQL*Plus: ALTER SESSION SET CURRENT_SCHEMA = SYS

If the maximum record retrieved property of the query is set to 10 then a

summary value will be calculated?

Only for 10 records.

What are the different objects that you cannot copy or reference in object

groups? Objects of different modules

Another object groups

Individual block dependent items

Program units.

What is an OLE? Object Linking & Embedding provides you with the capability to integrate objects

from many Ms-Windows applications into a single compound document creating

integrated applications enables you to use the features form .

Can a repeating frame be created without a data group as a base? No

Is it possible to set a filter condition in a cross product group in matrix reports? No

What is Overloading of procedures ? The Same procedure name is repeated with parameters of different datatypes and

parameters in different positions, varying number of parameters is called overloading

of procedures. e.g. DBMS_OUTPUT put_line

What are the return values of functions SQLCODE and SQLERRM ? What is

Pragma EXECPTION_INIT ? Explain the usage ? SQLCODE returns the latest code of the error that has occurred.

SQLERRM returns the relevant error message of the SQLCODE.

© Copyright : IT Engg Portal – www.itportal.in 486

What are the datatypes a available in PL/SQL ? Some scalar data types such as NUMBER, VARCHAR2, DATE, CHAR, LONG,

BOOLEAN. Some composite data types such as RECORD & TABLE.

What are the two parts of a procedure ? Procedure Specification and Procedure Body.

What is the basic structure of PL/SQL ? PL/SQL uses block structure as its basic structure. Anonymous blocks or nested

blocks can be used in PL/SQL

What is PL/SQL table ? Objects of type TABLE are called "PL/SQL tables", which are modeled as (but not the

same as) database tables, PL/SQL tables use a primary PL/SQL tables can have one

column and a primary key. Cursors

WHAT IS RMAN ? (for DBA) Recovery Manager is a tool that: manages the process of creating backups and also

manages the process of restoring and recovering from them.

WHY USE RMAN ? (for DBA) No extra costs …Its available free

?RMAN introduced in Oracle 8 it has become simpler with newer versions and easier

than user managed backups

?Proper security

?You are 100% sure your database has been backed up.

?Its contains detail of the backups taken etc in its central repository

Facility for testing validity of backups also commands like crosscheck to check the

status of backup.

Faster backups and restores compared to backups without RMAN

RMAN is the only backup tool which supports incremental backups.

Oracle 10g has got further optimized incremental backup which has resulted in

improvement of performance during backup and recovery time

Parallel operations are supported

Better querying facility for knowing different details of backup

No extra redo generated when backup is taken..compared to online

backup without RMAN which results in saving of space in hard disk

RMAN an intelligent tool

© Copyright : IT Engg Portal – www.itportal.in 487

Maintains repository of backup metadata

Remembers backup set location

Knows what need to backed up

Knows what is required for recovery

Knows what backups are redundant

UNDERSTANDING THE RMAN ARCHITECTURE An oracle RMAN comprises of

RMAN EXECUTABLE This could be present and fired even through client side

TARGET DATABASE This is the database which needs to be backed up .

RECOVERY CATALOG Recovery catalog is optional otherwise backup details are

stored in target database controlfile .

It is a repository of information queried and updated by Recovery Manager

It is a schema or user stored in Oracle database. One schema can support many

databases

It contains information about physical schema of target database datafile and archive

log ,backup sets and pieces Recovery catalog is a must in following scenarios

. In order to store scripts

. For tablespace point in time recovery

Media Management Software

Media Management software is a must if you are using RMAN for storing backup in

tape drive directly.

Backups in RMAN

Oracle backups in RMAN are of the following type

RMAN complete backup OR RMAN incremental backup

These backups are of RMAN proprietary nature

IMAGE COPY

The advantage of uing Image copy is its not in RMAN proprietary format..

Backup Format

RMAN backup is not in oracle format but in RMAN format. Oracle backup comprises

of backup sets and it consists of backup pieces. Backup sets are logical entity In oracle

9i it gets stored in a default location There are two type of backup sets Datafile backup

sets, Archivelog backup sets One more important point of data file backup sets is it do

© Copyright : IT Engg Portal – www.itportal.in 488

not include empty blocks. A backup set would contain many backup pieces.

A single backup piece consists of physical files which are in RMAN proprietary

format.

Example of taking backup using RMAN

Taking RMAN Backup

In non archive mode in dos prompt type

RMAN

You get the RMAN prompt

RMAN > Connect Target

Connect to target database : Magic

using target database controlfile instead of recovery catalog

Lets take a simple backup of database in non archive mode

shutdown immediate ; - - Shutdowns the database

startup mount

backup database ;- its start backing the database

alter database open;

We can fire the same command in archive log mode

And whole of datafiles will be backed

Backup database plus archivelog;

Restoring database

Restoring database has been made very simple in 9i .

It is just

Restore database..

RMAN has become intelligent to identify which datafiles has to be restored

and the location of backuped up file.

Oracle Enhancement for RMAN in 10 G

Flash Recovery Area

Right now the price of hard disk is falling. Many dba are taking oracle database

backup inside the hard disk itself since it results in lesser mean time between

recoverability.

The new parameter introduced is

DB_RECOVERY_FILE_DEST = /oracle/flash_recovery_area

© Copyright : IT Engg Portal – www.itportal.in 489

By configuring the RMAN RETENTION POLICY the flash recovery area will

automatically delete obsolete backups and archive logs that are no longer required

based on that configuration Oracle has introduced new features in incremental backup

Change Tracking File

Oracle 10g has the facility to deliver faster incrementals with the implementation of

changed tracking file feature.This will results in faster backups lesser space

consumption and also reduces the time needed for daily backups

Incrementally Updated Backups

Oracle database 10g Incrementally Updates Backup features merges the image copy of

a datafile with RMAN incremental backup. The resulting image copy is now updated

with block changes captured by incremental backups.The merging of the image copy

and incremental backup is initiated with RMAN recover command. This results in

faster recovery.

Binary compression technique reduces backup space usage by 50-75%.

With the new DURATION option for the RMAN BACKUP command, DBAs can

weigh backup performance against system service level requirements. By specifying a

duration, RMAN will automatically calculate the appropriate backup rate; in addition,

DBAs can optionally specify whether backups should minimize time or system load.

New Features in Oem to identify RMAN related backup like backup pieces, backup

sets and image copy

Oracle 9i New features Persistent RMAN Configuration

A new configure command has been introduced in Oracle 9i , that lets you configure

various features including automatic channels, parallelism ,backup options, etc.

These automatic allocations and options can be overridden by commands in a RMAN

command file.

Controlfile Auto backups

Through this new feature RMAN will automatically perform a controlfile auto backup.

after every backup or copy command.

Block Media Recovery

© Copyright : IT Engg Portal – www.itportal.in 490

If we can restore a few blocks rather than an entire file we only need few blocks.

We even dont need to bring the data file offline.

Syntax for it as follows

Block Recover datafile 8 block 22;

Configure Backup Optimization Prior to 9i whenever we backed up database using RMAN our backup also used take

backup of read only table spaces which had already been backed up and also the same

with archive log too.

Now with 9i backup optimization parameter we can prevent repeat backup of read

only tablespace and archive log. The command for this is as follows Configure backup

optimization on

Archive Log failover If RMAN cannot read a block in an archived log from a destination. RMAN

automatically attempts to read from an alternate location this is called as archive log

failover

There are additional commands like

backup database not backed up since time '31-jan-2002 14:00:00'

Do not backup previously backed up files

(say a previous backup failed and you want to restart from where it left off).

Similar syntax is supported for restores

backup device sbt backup set all Copy a disk backup to tape

(backing up a backup

Additionally it supports

. Backup of server parameter file

. Parallel operation supported

. Extensive reporting available

. Scripting

. Duplex backup sets

. Corrupt block detection

. Backup archive logs

Pitfalls of using RMAN

Previous to version Oracle 9i backups were not that easy which means you had to

allocate a channel compulsorily to take backup You had to give a run etc . The syntax

© Copyright : IT Engg Portal – www.itportal.in 491

was a bit complex …RMAN has now become very simple and easy to use..

If you changed the location of backup set it is compulsory for you to register it using

RMAN or while you are trying to restore backup It resulted in hanging situations

There is no method to know whether during recovery database restore is going to fail

because of missing archive log file.

Compulsory Media Management only if using tape backup

Incremental backups though used to consume less space used to be slower since it

used to read the entire database to find the changed blocks and also They have difficult

time streaming the tape device. .

Considerable improvement has been made in 10g to optimize the algorithm to handle

changed block.

Observation Introduced in Oracle 8 it has become more powerful and simpler with newer version

of Oracle 9 and 10 g.

So if you really don't want to miss something critical please start using RMAN.

Explain UNION,MINUS,UNION ALL, INTERSECT ?

INTERSECT returns all distinct rows selected by both queries.MINUS - returns all

distinct rows selected by the first query but not by the second.UNION - returns all

distinct rows selected by either queryUNION ALL - returns all rows selected by either

query, including all duplicates.

Should the OEM Console be displayed at all times (when there are scheduled

jobs)? (for DBA) When a job is submitted the agent will confirm the status of the job. When the status

shows up as scheduled, you can close down the OEM console. The processing of the

job is managed by the OIA (Oracle Intelligent Agent). The OIA maintains a .jou file in

the agent's subdirectory. When the console is launched communication with the Agent

is established and the contents of the .jou file (binary) are reported to the console job

subsystem. Note that OEM will not be able to send e-mail and paging notifications

when the Console is not started.

Difference between SUBSTR and INSTR ? INSTR (String1,String2(n,(m)),INSTR returns the position of the mth occurrence of

the string 2 instring1. The search begins from nth position of string1.SUBSTR

© Copyright : IT Engg Portal – www.itportal.in 492

(String1 n,m)SUBSTR returns a character string of size m in string1, starting from nth

position of string1.

What kind of jobs can one schedule with OEM? (for DBA) OEM comes with pre-defined jobs like Export, Import, run OS commands, run sql

scripts, SQL*Plus commands etc. It also gives you the flexibility of scheduling custom

jobs written with the TCL language.

What are the pre requisites ? I. to modify data type of a column ? ii. to add a column with NOT NULL constraint ?

To Modify the datatype of a column the column must be empty. to add a column with

NOT NULL constrain, the table must be empty.

How does one backout events and jobs during maintenance slots? (for DBA) Managemnet and data collection activity can be suspended by imposing a blackout.

Look at these examples:

agentctl start blackout # Blackout the entrire agent

agentctl stop blackout # Resume normal monitoring and management

agentctl start blackout ORCL # Blackout database ORCL

agentctl stop blackout ORCL # Resume normal monitoring and management

agentctl start blackout -s jobs -d 00:20 # Blackout jobs for 20 minutes

What are the types of SQL Statement ? Data Definition Language :

CREATE,ALTER,DROP,TRUNCATE,REVOKE,NO AUDIT & COMMIT.

Data Manipulation Language:

INSERT,UPDATE,DELETE,LOCK

TABLE,EXPLAIN PLAN & SELECT.Transactional Control:

COMMIT & ROLLBACKSession Control: ALTERSESSION & SET

ROLESystem Control :

ALTER SYSTEM.

What is the Oracle Intelligent Agent? (for DBA) The Oracle Intelligent Agent (OIA) is an autonomous process that needs to run on a

remote node in the network to make the node OEM manageable. The Oracle

© Copyright : IT Engg Portal – www.itportal.in 493

Intelligent Agent is responsible for:

. Discovering targets that can be managed (Database Servers, Net8 Listeners, etc.);

. Monitoring of events registered in Enterprise Manager; and

. Executing tasks associated with jobs submitted to Enterprise Manager.

How does one start the Oracle Intelligent Agent? (for DBA) One needs to start an OIA (Oracle Intelligent Agent) process on all machines that will

to be managed via OEM.

For OEM 9i and above:

agentctl start agent

agentctl stop agent

For OEM 2.1 and below:

lsnrctl dbsnmp_start

lsnrctl dbsnmp_status

On Windows NT, start the "OracleAgent" Service.

If the agent doesn't want to start, ensure your environment variables are set correctly

and delete the following files before trying again:

1) In $ORACLE_HOME/network/admin: snmp_ro.ora and snmp_rw.ora.

2) Also delete ALL files in $ORACLE_HOME/network/agent/.

Can one write scripts to send alert messages to the console? Start the OEM console and create a new event. Select option "Enable Unsolicited

Event". Select test "Unsolicited Event". When entering the parameters, enter values

similar to these:

Event Name: /oracle/script/myalert

Object: *

Severity: *

Message: *

One can now write the script and invoke the oemevent command to send alerts to the

console. Look at this example: oemevent /oracle/script/myalert DESTINATION alert

"My custom error message" where DESTINATION is the same value as entered in the

"Monitored Destinations" field when you've registered the event in the OEM Console.

Where can one get more information about TCL? (for DBA) One can write custom event checking routines for OEM using the TCL (Tool

© Copyright : IT Engg Portal – www.itportal.in 494

Command Language) language. Check the following sites for more information about

TCL:

. The Tcl Developer Xchange - download and learn about TCL

. OraTCL at Sourceforge - Download the OraTCL package

. Tom Poindexter's Tcl Page - Oratcl was originally written by Tom Poindexter

Are there any troubleshooting tips for OEM? (for DBA) . Create the OEM repository with a user (which will manage the OEM) and store it in

a tablespace that does not share any data with other database users. It is a bad practice

to create the repository with SYS and System.

. If you are unable to launch the console or there is a communication problem with the

intelligent agent (daemon). Ensure OCX files are registered. Type the following in the

DOS prompt (the current directory should be $ORACLE_HOME\BIN:

C:\Orawin95\Bin> RegSvr32 mmdx32.OCX

C:\Orawin95\Bin> RegSvr32 vojt.OCX

. If you have a problem starting the Oracle Agent

Solution A: Backup the *.Q files and Delete all the *.Q Files

($Oracle_home/network/agent folder)

Backup and delete SNMP_RO.ora, SNMP_RW.ora, dbsnmp.ver and services.ora files

($Oracle_Home/network/admin folder) Start the Oracle Agent service.

Solution B: Your version of Intelligent Agent could be buggy. Check with Oracle for

any available patches. For example, the Intelligent Agent that comes with Oracle 8.0.4

is buggy.

Sometimes you get a Failed status for the job that was executed successfully.

Check the log to see the results of the execution rather than relying on this status.

What is import/export and why does one need it? (for DBA) The Oracle export (EXP) and import (IMP) utilities are used to perform logical

database backup and recovery. They are also used to move Oracle data from one

machine, database or schema to another.

The imp/exp utilities use an Oracle proprietary binary file format and can thus only be

used between Oracle databases. One cannot export data and expect to import it into a

non-Oracle database. For more information on how to load and unload data from files,

read the SQL*Loader FAQ.

The export/import utilities are also commonly used to perform the following tasks:

. Backup and recovery (small databases only)

. Reorganization of data/ Eliminate database fragmentation

© Copyright : IT Engg Portal – www.itportal.in 495

. Detect database corruption. Ensure that all the data can be read.

. Transporting tablespaces between databases

. Etc.

What is a display item? Display items are similar to text items but store only fetched or assigned values.

Operators cannot navigate to a display item or edit the value it contains.

How does one use the import/export utilities? (for DBA) Look for the "imp" and "exp" executables in your $ORACLE_HOME/bin directory.

One can run them interactively, using command line parameters, or using parameter

files. Look at the imp/exp parameters before starting. These parameters can be listed

by executing the following commands: "exp help=yes" or "imp help=yes".

The following examples demonstrate how the imp/exp utilities can be used:

exp scott/tiger file=emp.dmp log=emp.log tables=emp rows=yes indexes=no

exp scott/tiger file=emp.dmp tables=(emp,dept)

imp scott/tiger file=emp.dmp full=yes

imp scott/tiger file=emp.dmp fromuser=scott touser=scott tables=dept

exp userid=scott/tiger@orcl parfile=export.txt

... where export.txt contains:

BUFFER=100000

FILE=account.dmp

FULL=n

OWNER=scott

GRANTS=y

COMPRESS=y

NOTE: If you do not like command line utilities, you can import and export data with

the "Schema Manager" GUI that ships with Oracle Enterprise Manager (OEM).

What are the types of visual attribute settings? Custom Visual attributes Default visual attributes Named Visual attributes. Window

Can one export a subset of a table? (for DBA) From Oracle8i one can use the QUERY= export parameter to selectively unload a

subset of the data from a table. Look at this example:

exp scott/tiger tables=emp query=\"where deptno=10\"

© Copyright : IT Engg Portal – www.itportal.in 496

What are the two ways to incorporate images into a oracle forms application? Boilerplate Images

Image_items

Can one monitor how fast a table is imported? (for DBA) If you need to monitor how fast rows are imported from a running import job, try one

of the following methods:

Method 1:

select substr(sql_text,instr(sql_text,'INTO "'),30) table_name,

rows_processed,

round((sysdate-to_date(first_load_time,'yyyy-mm-dd hh24:mi:ss'))*24*60,1) minutes,

trunc(rows_processed/((sysdate-to_date(first_load_time,'yyyy-mm-dd

hh24:mi:ss'))*24*60)) rows_per_min

from sys.v_$sqlarea

where sql_text like 'INSERT %INTO "%'

and command_type = 2

and open_versions > 0;

For this to work one needs to be on Oracle 7.3 or higher (7.2 might also be OK). If the

import has more than one table, this statement will only show information about the

current table being imported.

Contributed by Osvaldo Ancarola, Bs. As. Argentina.

Method 2:

Use the FEEDBACK=n import parameter. This command will tell IMP to display a

dot for every N rows imported.

Can one import tables to a different tablespace? (for DBA) Oracle offers no parameter to specify a different tablespace to import data into.

Objects will be re-created in the tablespace they were originally exported from. One

can alter this behaviour by following one of these procedures: Pre-create the table(s) in

the correct tablespace:

. Import the dump file using the INDEXFILE= option

. Edit the indexfile. Remove remarks and specify the correct tablespaces.

. Run this indexfile against your database, this will create the required tables in the

appropriate tablespaces

. Import the table(s) with the IGNORE=Y option.

Change the default tablespace for the user:

© Copyright : IT Engg Portal – www.itportal.in 497

. Revoke the "UNLIMITED TABLESPACE" privilege from the user

. Revoke the user's quota from the tablespace from where the object was exported.

This forces the import utility to create tables in the user's default tablespace.

. Make the tablespace to which you want to import the default tablespace for the user

. Import the table

What do you mean by a block in forms4.0? Block is a single mechanism for grouping related items into a functional unit for

storing, displaying and manipulating records.

How is possible to restrict the user to a list of values while entering values for

parameters? By setting the Restrict To List property to true in the parameter property sheet.

What is SQL*Loader and what is it used for? (for DBA) SQL*Loader is a bulk loader utility used for moving data from external files into the

Oracle database. Its syntax is similar to that of the DB2 Load utility, but comes with

more options. SQL*Loader supports various load formats, selective loading, and

multi-table loads.

How does one use the SQL*Loader utility? (for DBA) One can load data into an Oracle database by using the sqlldr (sqlload on some

platforms) utility. Invoke the utility without arguments to get a list of available

parameters. Look at the following example:

sqlldr scott/tiger control=loader.ctl

This sample control file (loader.ctl) will load an external data file containing delimited

data:

load data

infile 'c:\data\mydata.csv'

into table emp

fields terminated by "," optionally enclosed by '"'

( empno, empname, sal, deptno )

The mydata.csv file may look like this:

10001,"Scott Tiger", 1000, 40

10002,"Frank Naude", 500, 20

Another Sample control file with in-line data formatted as fix length records. The trick

is to specify "*" as the name of the data file, and use BEGINDATA to start the data

section in the control file.

© Copyright : IT Engg Portal – www.itportal.in 498

load data

infile *

replace

into table departments

( dept position (02:05) char(4),

deptname position (08:27) char(20)

)

begindata

COSC COMPUTER SCIENCE

ENGL ENGLISH LITERATURE

MATH MATHEMATICS

POLY POLITICAL SCIENCE

How can a cross product be created?

By selecting the cross products tool and drawing a new group surrounding the base

group of the cross products.

Is there a SQL*Unloader to download data to a flat file? (for DBA) Oracle does not supply any data unload utilities. However, you can use SQL*Plus to

select and format your data and then spool it to a file:

set echo off newpage 0 space 0 pagesize 0 feed off head off trimspool on

spool oradata.txt

select col1 || ',' || col2 || ',' || col3

from tab1

where col2 = 'XYZ';

spool off

Alternatively use the UTL_FILE PL/SQL package:

rem Remember to update initSID.ora, utl_file_dir='c:\oradata' parameter

declare

fp utl_file.file_type;

begin

fp := utl_file.fopen('c:\oradata','tab1.txt','w');

utl_file.putf(fp, '%s, %s\n', 'TextField', 55);

utl_file.fclose(fp);

end;

/

You might also want to investigate third party tools like SQLWays from Ispirer

© Copyright : IT Engg Portal – www.itportal.in 499

Systems, TOAD from Quest, or ManageIT Fast Unloader from CA to help you unload

data from Oracle.

Can one load variable and fix length data records? (for DBA) Yes, look at the following control file examples. In the first we will load delimited

data (variable length):

LOAD DATA

INFILE *

INTO TABLE load_delimited_data

FIELDS TERMINATED BY "," OPTIONALLY ENCLOSED BY '"'

TRAILING NULLCOLS

( data1,

data2

)

BEGINDATA

11111,AAAAAAAAAA

22222,"A,B,C,D,"

If you need to load positional data (fixed length), look at the following control file

example:

LOAD DATA

INFILE *

INTO TABLE load_positional_data

( data1 POSITION(1:5),

data2 POSITION(6:15)

)

BEGINDATA

11111AAAAAAAAAA

22222BBBBBBBBBB

Can one skip header records load while loading?

Use the "SKIP n" keyword, where n = number of logical rows to skip. Look at this

example:

LOAD DATA

INFILE *

INTO TABLE load_positional_data

SKIP 5

( data1 POSITION(1:5),

data2 POSITION(6:15)

© Copyright : IT Engg Portal – www.itportal.in 500

)

BEGINDATA

11111AAAAAAAAAA

22222BBBBBBBBBB

Can one modify data as it loads into the database? (for DBA) Data can be modified as it loads into the Oracle Database. Note that this only applies

for the conventional load path and not for direct path loads.

LOAD DATA

INFILE *

INTO TABLE modified_data

( rec_no "my_db_sequence.nextval",

region CONSTANT '31',

time_loaded "to_char(SYSDATE, 'HH24:MI')",

data1 POSITION(1:5) ":data1/100",

data2 POSITION(6:15) "upper(:data2)",

data3 POSITION(16:22)"to_date(:data3, 'YYMMDD')"

)

BEGINDATA

11111AAAAAAAAAA991201

22222BBBBBBBBBB990112

LOAD DATA

INFILE 'mail_orders.txt'

BADFILE 'bad_orders.txt'

APPEND

INTO TABLE mailing_list

FIELDS TERMINATED BY ","

( addr,

city,

state,

zipcode,

mailing_addr "decode(:mailing_addr, null, :addr, :mailing_addr)",

mailing_city "decode(:mailing_city, null, :city, :mailing_city)",

mailing_state

)

© Copyright : IT Engg Portal – www.itportal.in 501

Can one load data into multiple tables at once? (for DBA) Look at the following control file:

LOAD DATA

INFILE *

REPLACE

INTO TABLE emp

WHEN empno != ' '

( empno POSITION(1:4) INTEGER EXTERNAL,

ename POSITION(6:15) CHAR,

deptno POSITION(17:18) CHAR,

mgr POSITION(20:23) INTEGER EXTERNAL

)

INTO TABLE proj

WHEN projno != ' '

( projno POSITION(25:27) INTEGER EXTERNAL,

empno POSITION(1:4) INTEGER EXTERNAL

)

What is the difference between boiler plat images and image items? Boiler plate Images are static images (Either vector or bit map) that you import from

the file system or database to use a graphical elements in your form, such as company

logos and maps. Image items are special types of interface controls that store and

display either vector or bitmap images. Like other items that store values, image items

can be either base table items(items that relate directly to database columns) or control

items. The definition of an image item is stored as part of the form module FMB and

FMX files, but no image file is actually associated with an image item until the item is

populate at run time.

What are the triggers available in the reports?

Before report, Before form, After form , Between page, After report.

Why is a Where clause faster than a group filter or a format trigger? Because, in a where clause the condition is applied during data retrievalthan after

retrieving the data.

Can one selectively load only the records that one need? (for DBA) Look at this example, (01) is the first character, (30:37) are characters 30 to 37:

LOAD DATA

© Copyright : IT Engg Portal – www.itportal.in 502

INFILE 'mydata.dat' BADFILE 'mydata.bad' DISCARDFILE 'mydata.dis'

APPEND

INTO TABLE my_selective_table

WHEN (01) <> 'H' and (01) <> 'T' and (30:37) = '19991217'

(

region CONSTANT '31',

service_key POSITION(01:11) INTEGER EXTERNAL,

call_b_no POSITION(12:29) CHAR

)

Can one skip certain columns while loading data? (for DBA) One cannot use POSTION(x:y) with delimited data. Luckily, from Oracle 8i one can

specify FILLER columns. FILLER columns are used to skip columns/fields in the load

file, ignoring fields that one does not want. Look at this example: -- One cannot use

POSTION(x:y) as it is stream data, there are no positional fields-the next field begins

after some delimiter, not in column X. -->

LOAD DATA

TRUNCATE INTO TABLE T1

FIELDS TERMINATED BY ','

( field1,

field2 FILLER,

field3

)

How does one load multi-line records? (for DBA) One can create one logical record from multiple physical records using one of the

following two clauses:

. CONCATENATE: - use when SQL*Loader should combine the same number of

physical records together to form one logical record.

. CONTINUEIF - use if a condition indicates that multiple records should be treated as

one. Eg. by having a '#' character in column 1.

How can get SQL*Loader to COMMIT only at the end of the load file? (for

DBA) One cannot, but by setting the ROWS= parameter to a large value, committing can be

reduced. Make sure you have big rollback segments ready when you use a high value

for ROWS=.

© Copyright : IT Engg Portal – www.itportal.in 503

Can one improve the performance of SQL*Loader? (for DBA) A very simple but easily overlooked hint is not to have any indexes and/or constraints

(primary key) on your load tables during the load process. This will significantly slow

down load times even with ROWS= set to a high value.

Add the following option in the command line: DIRECT=TRUE. This will effectively

bypass most of the RDBMS processing. However, there are cases when you can't use

direct load. Refer to chapter 8 on Oracle server Utilities manual.

Turn off database logging by specifying the UNRECOVERABLE option. This option

can only be used with direct data loads. Run multiple load jobs concurrently.

How does one use SQL*Loader to load images, sound clips and documents? (for

DBA) SQL*Loader can load data from a "primary data file", SDF (Secondary Data file - for

loading nested tables and VARRAYs) or LOGFILE. The LOBFILE method provides

and easy way to load documents, images and audio clips into BLOB and CLOB

columns. Look at this example:

Given the following table:

CREATE TABLE image_table (

image_id NUMBER(5),

file_name VARCHAR2(30),

image_data BLOB);

Control File:

LOAD DATA

INFILE *

INTO TABLE image_table

REPLACE

FIELDS TERMINATED BY ','

(

image_id INTEGER(5),

file_name CHAR(30),

image_data LOBFILE (file_name) TERMINATED BY EOF

)

BEGINDATA

001,image1.gif

002,image2.jpg

© Copyright : IT Engg Portal – www.itportal.in 504

What is the difference between the conventional and direct path loader? (for

DBA) The conventional path loader essentially loads the data by using standard INSERT

statements. The direct path loader (DIRECT=TRUE) bypasses much of the logic

involved with that, and loads directly into the Oracle data files. More information

about the restrictions of direct path loading can be obtained from the Utilities Users

Guide.

GENERAL INTERVIEW QUESTIONS

What are the various types of Exceptions ? User defined and Predefined Exceptions.

Can we define exceptions twice in same block ? No.

What is the difference between a procedure and a function ? Functions return a single variable by value whereas procedures do not return any

variable by value. Rather they return multiple variables by passing variables by

reference through their OUT parameter.

Can you have two functions with the same name in a PL/SQL block ? Yes.

Can you have two stored functions with the same name ? Yes.

Can you call a stored function in the constraint of a table ? No.

What are the various types of parameter modes in a procedure ? IN, OUT AND INOUT.

What is Over Loading and what are its restrictions ? OverLoading means an object performing different functions depending upon the no.

of parameters or the data type of the parameters passed to it.

Can functions be overloaded ? Yes.

© Copyright : IT Engg Portal – www.itportal.in 505

Can 2 functions have same name & input parameters but differ only by return

datatype ? No.

What are the constructs of a procedure, function or a package ? The constructs of a procedure, function or a package are :

variables and constants

cursors

exceptions

Why Create or Replace and not Drop and recreate procedures ? So that Grants are not dropped.

Can you pass parameters in packages ? How ? Yes. You can pass parameters to procedures or functions in a package.

What are the parts of a database trigger ? The parts of a trigger are:

A triggering event or statement

A trigger restriction

A trigger action

What are the various types of database triggers ? There are 12 types of triggers, they are combination of :

Insert, Delete and Update Triggers.

Before and After Triggers.

Row and Statement Triggers.

(3*2*2=12)

What is the advantage of a stored procedure over a database trigger ?

We have control over the firing of a stored procedure but we have no control over the

firing of a trigger.

What is the maximum no. of statements that can be specified in a trigger

statement ? One.

Can views be specified in a trigger statement ? No

© Copyright : IT Engg Portal – www.itportal.in 506

What are the values of :new and :old in Insert/Delete/Update Triggers ? INSERT : new = new value, old = NULL

DELETE : new = NULL, old = old value

UPDATE : new = new value, old = old value

What are cascading triggers? What is the maximum no of cascading triggers at a

time? When a statement in a trigger body causes another trigger to be fired, the triggers are

said to be cascading. Max = 32.

What are mutating triggers ? A trigger giving a SELECT on the table on which the trigger is written.

What are constraining triggers ? A trigger giving an Insert/Update on a table having referential integrity constraint on

the triggering table.

Describe Oracle database's physical and logical structure ? Physical : Data files, Redo Log files, Control file.

Logical : Tables, Views, Tablespaces, etc.

Can you increase the size of a tablespace ? How ? Yes, by adding datafiles to it.

What is the use of Control files ? Contains pointers to locations of various data files, redo log files, etc.

What is the use of Data Dictionary ? Used by Oracle to store information about various physical and logical Oracle

structures e.g. Tables, Tablespaces, datafiles, etc

What are the advantages of clusters ? Access time reduced for joins.

What are the disadvantages of clusters ? The time for Insert increases.

Can Long/Long RAW be clustered ? No.

© Copyright : IT Engg Portal – www.itportal.in 507

Can null keys be entered in cluster index, normal index ? Yes.

Can Check constraint be used for self referential integrity ? How ? Yes. In the CHECK condition for a column of a table, we can reference some other

column of the same table and thus enforce self referential integrity.

What are the min. extents allocated to a rollback extent ? Two

What are the states of a rollback segment ? What is the difference between partly

available and needs recovery ? The various states of a rollback segment are :

ONLINE, OFFLINE, PARTLY AVAILABLE, NEEDS RECOVERY and INVALID.

What is the difference between unique key and primary key ? Unique key can be null; Primary key cannot be null.

An insert statement followed by a create table statement followed by rollback ?

Will the rows be inserted ? No.

an you define multiple savepoints ? Yes.

Can you Rollback to any savepoint ? Yes.

What is the maximum no. of columns a table can have ? 254.

What is the significance of the & and && operators in PL SQL ? The & operator means that the PL SQL block requires user input for a variable. The

&& operator means that the value of this variable should be the same as inputted by

the user previously for this same variable. If a transaction is very large, and the

rollback segment is not able to hold the rollback information, then will the transaction

span across different rollback segments or will it terminate ? It will terminate (Please

check ).

© Copyright : IT Engg Portal – www.itportal.in 508

Can you pass a parameter to a cursor ? Explicit cursors can take parameters, as the example below shows. A cursor parameter

can appear in a query wherever a constant can appear. CURSOR c1 (median IN

NUMBER) IS SELECT job, ename FROM emp WHERE sal > median;

What are the various types of RollBack Segments ? Public Available to all instances

Private Available to specific instance

Can you use %RowCount as a parameter to a cursor ? Yes

Is the query below allowed :

Select sal, ename Into x From emp Where ename = 'KING'

(Where x is a record of Number(4) and Char(15)) Yes

Is the assignment given below allowed :

ABC = PQR (Where ABC and PQR are records) Yes

Is this for loop allowed :

For x in &Start..&End Loop Yes

How many rows will the following SQL return :

Select * from emp Where rownum < 10; 9 rows

How many rows will the following SQL return :

Select * from emp Where rownum = 10; No rows

Which symbol preceeds the path to the table in the remote database ? @

Are views automatically updated when base tables are updated ? Yes

© Copyright : IT Engg Portal – www.itportal.in 509

Can a trigger written for a view ? No

If all the values from a cursor have been fetched and another fetch is issued, the

output will be : error, last record or first record ? Last Record

A table has the following data : [[5, Null, 10]]. What will the average function

return ? 7.5

Is Sysdate a system variable or a system function? System Function

Consider a sequence whose currval is 1 and gets incremented by 1 by using the

nextval reference we get the next number 2. Suppose at this point we issue an

rollback and again issue a nextval. What will the output be ? 3

Definition of relational DataBase by Dr. Codd (IBM)? A Relational Database is a database where all data visible to the user is organized

strictly as tables of data values and where all database operations work on these tables.

What is Multi Threaded Server (MTA) ? In a Single Threaded Architecture (or a dedicated server configuration) the database

manager creates a separate process for each database user. But in MTA the database

manager can assign multiple users (multiple user processes) to a single dispatcher

(server process), a controlling process that queues request for work thus reducing the

databases memory requirement and resources.

Which are initial RDBMS, Hierarchical & N/w database ? RDBMS - R system

Hierarchical - IMS

N/W - DBTG

What is Functional Dependency Given a relation R, attribute Y of R is functionally dependent on attribute X of R if

and only if each X-value has associated with it precisely one -Y value in R

© Copyright : IT Engg Portal – www.itportal.in 510

What is Auditing ?

The database has the ability to audit all actions that take place within it.

a) Login attempts, b) Object Accesss, c) Database Action Result of Greatest(1,NULL)

or Least(1,NULL) NULL

While designing in client/server what are the 2 imp. things to be considered ? Network Overhead (traffic), Speed and Load of client server

When to create indexes ? To be created when table is queried for less than 2% or 4% to 25% of the table rows.

How can you avoid indexes ? TO make index access path unavailable - Use FULL hint to optimizer for full table

scan - Use INDEX or AND-EQUAL hint to optimizer to use one index or set to

indexes instead of another. - Use an expression in the Where Clause of the SQL.

What is the result of the following SQL :

Select 1 from dual

UNION

Select 'A' from dual; Error

Can database trigger written on synonym of a table and if it can be then what

would be the effect if original table is accessed. Yes, database trigger would fire.

Can you alter synonym of view or view ? No

Can you create index on view ? No

What is the difference between a view and a synonym ? Synonym is just a second name of table used for multiple link of database. View can

be created with many tables, and with virtual columns and with conditions. But

synonym can be on view.

© Copyright : IT Engg Portal – www.itportal.in 511

What is the difference between alias and synonym ? Alias is temporary and used with one query. Synonym is permanent and not used as

alias.

What is the effect of synonym and table name used in same Select statement ? Valid

What's the length of SQL integer ? 32 bit length

What is the difference between foreign key and reference key ? Foreign key is the key i.e. attribute which refers to another table primary key.

Reference key is the primary key of table referred by another table.

Can dual table be deleted, dropped or altered or updated or inserted ? Yes

If content of dual is updated to some value computation takes place or not ? Yes

If any other table same as dual is created would it act similar to dual? Yes

For which relational operators in where clause, index is not used ? <> , like '% ...' is NOT functions, field +constant, field || ''

Assume that there are multiple databases running on one machine. How can you

switch from one to another ? Changing the ORACLE_SID

What are the advantages of Oracle ? Portability : Oracle is ported to more platforms than any of its competitors, running on

more than 100 hardware platforms and 20 networking protocols.

Market Presence : Oracle is by far the largest RDBMS vendor and spends more on R

& D than most of its competitors earn in total revenue. This market clout means that

you are unlikely to be left in the lurch by Oracle and there are always lots of third

party interfaces available.

Backup and Recovery : Oracle provides industrial strength support for on-line backup

and recovery and good software fault tolerence to disk failure. You can also do point-

© Copyright : IT Engg Portal – www.itportal.in 512

in-time recovery.

Performance : Speed of a 'tuned' Oracle Database and application is quite good, even

with large databases. Oracle can manage > 100GB databases.

Multiple database support : Oracle has a superior ability to manage multiple databases

within the same transaction using a two-phase commit protocol.

What is a forward declaration ? What is its use ? PL/SQL requires that you declare an identifier before using it. Therefore, you must

declare a subprogram before calling it. This declaration at the start of a subprogram is

called forward declaration. A forward declaration consists of a subprogram

specification terminated by a semicolon.

What are actual and formal parameters ? Actual Parameters : Subprograms pass information using parameters. The variables or

expressions referenced in the parameter list of a subprogram call are actual

parameters. For example, the following procedure call lists two actual parameters

named emp_num and amount:

Eg. raise_salary(emp_num, amount);

Formal Parameters : The variables declared in a subprogram specification and

referenced in the subprogram body are formal parameters. For example, the following

procedure declares two formal parameters named emp_id and increase: Eg.

PROCEDURE raise_salary (emp_id INTEGER, increase REAL) IS current_salary

REAL;

What are the types of Notation ? Position, Named, Mixed and Restrictions.

What all important parameters of the init.ora are supposed to be increased if you

want to increase the SGA size ? In our case, db_block_buffers was changed from 60 to 1000 (std values are 60, 550 &

3500) shared_pool_size was changed from 3.5MB to 9MB (std values are 3.5, 5 &

9MB) open_cursors was changed from 200 to 300 (std values are 200 & 300)

db_block_size was changed from 2048 (2K) to 4096 (4K) {at the time of database

creation}.

The initial SGA was around 4MB when the server RAM was 32MB and The new

SGA was around 13MB when the server RAM was increased to 128MB.

© Copyright : IT Engg Portal – www.itportal.in 513

If I have an execute privilege on a procedure in another users schema, can I

execute his procedure even though I do not have privileges on the tables within

the procedure ? Yes

What are various types of joins ? Equijoins, Non-equijoins, self join, outer join

What is a package cursor ? A package cursor is a cursor which you declare in the package specification without an

SQL statement. The SQL statement for the cursor is attached dynamically at runtime

from calling procedures.

If you insert a row in a table, then create another table and then say Rollback. In

this case will the row be inserted ?

Yes. Because Create table is a DDL which commits automatically as soon as it is

executed. The DDL commits the transaction even if the create statement fails

internally (eg table already exists error) and not syntactically.

What are the various types of queries ?? Normal Queries

Sub Queries

Co-related queries

Nested queries

Compound queries

What is a transaction ? A transaction is a set of SQL statements between any two COMMIT and ROLLBACK

statements.

What is implicit cursor and how is it used by Oracle ? An implicit cursor is a cursor which is internally created by Oracle. It is created by

Oracle for each individual SQL.

Which of the following is not a schema object : Indexes, tables, public synonyms,

triggers and packages ? Public synonyms

© Copyright : IT Engg Portal – www.itportal.in 514

What is PL/SQL? PL/SQL is Oracle's Procedural Language extension to SQL. The language includes

object oriented programming techniques such as encapsulation, function overloading,

information hiding (all but inheritance), and so, brings state-of-the-art programming to

the Oracle database server and a variety of Oracle tools.

Is there a PL/SQL Engine in SQL*Plus? No. Unlike Oracle Forms, SQL*Plus does not have a PL/SQL engine. Thus, all your

PL/SQL are send directly to the database engine for execution. This makes it much

more efficient as SQL statements are not stripped off and send to the database

individually.

Is there a limit on the size of a PL/SQL block? Currently, the maximum parsed/compiled size of a PL/SQL block is 64K and the

maximum code size is 100K. You can run the following select statement to query the

size of an existing package or procedure.

SQL> select * from dba_object_size where name = 'procedure_name'

Can one read/write files from PL/SQL? Included in Oracle 7.3 is a UTL_FILE package that can read and write files. The

directory you intend writing to has to be in your INIT.ORA file (see

UTL_FILE_DIR=... parameter). Before Oracle 7.3 the only means of writing a file

was to use DBMS_OUTPUT with the SQL*Plus SPOOL command.

DECLARE

fileHandler UTL_FILE.FILE_TYPE;

BEGIN

fileHandler := UTL_FILE.FOPEN('/home/oracle/tmp', 'myoutput','W');

UTL_FILE.PUTF(fileHandler, 'Value of func1 is %sn', func1(1));

UTL_FILE.FCLOSE(fileHandler);

END;

How can I protect my PL/SQL source code? PL/SQL V2.2, available with Oracle7.2, implements a binary wrapper for PL/SQL

programs to protect the source code. This is done via a standalone utility that

transforms the PL/SQL source code into portable binary object code (somewhat larger

than the original). This way you can distribute software without having to worry about

exposing your proprietary algorithms and methods. SQL*Plus and SQL*DBA will

still understand and know how to execute such scripts. Just be careful, there is no

© Copyright : IT Engg Portal – www.itportal.in 515

"decode" command available.

The syntax is:

wrap iname=myscript.sql oname=xxxx.yyy

Can one use dynamic SQL within PL/SQL? OR Can you use a DDL in a

procedure ? How ? From PL/SQL V2.1 one can use the DBMS_SQL package to execute dynamic SQL

statements.

Eg: CREATE OR REPLACE PROCEDURE DYNSQL

AS

cur integer;

rc integer;

BEGIN

cur := DBMS_SQL.OPEN_CURSOR;

DBMS_SQL.PARSE(cur,'CREATE TABLE X (Y DATE)', DBMS_SQL.NATIVE);

rc := DBMS_SQL.EXECUTE(cur);

DBMS_SQL.CLOSE_CURSOR(cur);

END;

======================================================

© Copyright : IT Engg Portal – www.itportal.in 516

C

Aptitude

Questions &

Answers

© Copyright : IT Engg Portal – www.itportal.in 517

C Aptitude Questions

Note :All the programs are tested under Turbo C/C++ compilers.

It is assumed that,

Programs run under DOS environment,

The underlying machine is an x86 system,

Program is compiled using Turbo C/C++ compiler.

The program output may depend on the information based on this assumptions

(for example sizeof(int) == 2 may be assumed).

Predict the output or error(s) for the following:

Questions 1. void main()

{

int const * p=5;

printf("%d",++(*p));

}

Answer:Compiler error: Cannot modify a constant value.

Explanation:

p is a pointer to a "constant integer". But we tried to change the value of the

"constant integer".

Questions 2.

main()

{

© Copyright : IT Engg Portal – www.itportal.in 518

char s[ ]="man";

int i;

for(i=0;s[ i ];i++)

printf("\n%c%c%c%c",s[ i ],*(s+i),*(i+s),i[s]);

}

Answer: mmmm

aaaa

nnnn

Explanation:

s[i], *(i+s), *(s+i), i[s] are all different ways of expressing the same idea.

Generally array name is the base address for that array. Here s is the base

address. i is the index number/displacement from the base address. So, indirecting

it with * is same as s[i]. i[s] may be surprising. But in the case of C it is same as

s[i].

Questions 3. main()

{

float me = 1.1;

double you = 1.1;

if(me==you)

printf("I love U");

else

printf("I hate U");

}

© Copyright : IT Engg Portal – www.itportal.in 519

Answer:

I hate U

Explanation:

For floating point numbers (float, double, long double) the values cannot be

predicted exactly. Depending on the number of bytes, the precession with of the

value represented varies. Float takes 4 bytes and long double takes 10 bytes. So

float stores 0.9 with less precision than long double.

Rule of Thumb:

Never compare or at-least be cautious when using floating point numbers with

relational operators (== , >, <, <=, >=,!= )

Questions 4. main()

{

static int var = 5;

printf("%d ",var--);

if(var)

main();

}

Answer:

5 4 3 2 1

Explanation:

When static storage class is given, it is initialized once. The change in the value

of a static variable is retained even betweenthe function calls. Main is also treated

like any other ordinary function, which can be called recursively.

© Copyright : IT Engg Portal – www.itportal.in 520

Questions 5.

main()

{

int c[ ]={2.8,3.4,4,6.7,5};

int j,*p=c,*q=c;

for(j=0;j<5;j++) {

printf(" %d ",*c);

++q; }

for(j=0;j<5;j++){

printf(" %d ",*p);

++p; }

}

Answer:

2 2 2 2 2 2 3 4 6 5

Explanation:

Initially pointer c is assigned to both p and q. In the first loop, since only q is

incremented and not c , the value 2 will be printed 5 times. In second loop p itself

is incremented. So the values 2 3 4 6 5 will be printed.

Questions 6.

main()

{

extern int i;

© Copyright : IT Engg Portal – www.itportal.in 521

i=20;

printf("%d",i);

}

Answer:

Linker Error : Undefined symbol '_i'

Explanation: extern storage class in the following

declaration, extern int i;

specifies to the compiler that the memory for i is allocated in some other program

and that address will be given to the current program at the time of linking. But

linker finds that no other variable of name i is available in any other program with

memory space allocated for it. Hence a linker error has occurred .

Questions 7.

main()

{

int i=-1,j=-1,k=0,l=2,m;

m=i++&&j++&&k++||l++;

printf("%d %d %d %d %d",i,j,k,l,m);

}

Answer:

0 0 1 3 1

Explanation :Logical operations always give a result of 1 or 0 . And also the

logical AND (&&) operator has higher priority over the logical OR (||) operator.

So the expression ‗i++ && j++ && k++‘ is executed first. The result of this

expression is 0 (-1 && -1 && 0 = 0). Now the expression is 0 || 2 which

© Copyright : IT Engg Portal – www.itportal.in 522

evaluates to 1 (because OR operator always gives 1 except for ‗0 || 0‘

combination- for which it gives 0). So the value of m is 1. The values

of other variables are also incremented by 1.

Questions 8. main()

{

char *p;

printf("%d %d ",sizeof(*p),sizeof(p));

}

Answer:

1 2

Explanation:The sizeof() operator gives the number of bytes taken by its

operand. P is a character pointer, which needs one byte for storing its value (a

character). Hence sizeof(*p) gives a value of 1. Since it needs two bytes to store

the address of the character pointer sizeof(p) gives 2.

Questions 9.

main()

{

int i=3;

switch(i)

{

default:printf("zero");

case 1: printf("one");

break;

© Copyright : IT Engg Portal – www.itportal.in 523

case 2:printf("two");

break;

case 3: printf("three");

break;

}

}

Answer :

three

Explanation :

The default case can be placed anywhere inside the loop. It is executed only when

all other cases doesn't match.

Questions 10.

main()

{

printf("%x",-1<<4);

}

Answer: fff0

Explanation :-1 is internally represented as all 1's. When left shifted four times

the least significant 4 bits are filled with 0's.The %x format specified specifies

that the integer value be printed as a hexadecimal value.

Questions 11. main()

{

char string[]="Hello World";

© Copyright : IT Engg Portal – www.itportal.in 524

display(string);

}

void display(char *string)

{

printf("%s",string);

}

Answer: Compiler Error : Type mismatch in redeclaration of function display

Explanation :

In third line, when the function display is encountered, the compiler doesn't know

anything about the function display. It assumes the arguments and return types to

be integers, (which is the default type). When it sees the actual function display,

the arguments and type contradicts with what it has assumed previously. Hence a

compile time error occurs.

Questions 12. main()

{

int c=- -2;

printf("c=%d",c);

}

Answer: c=2;

Explanation:Here unary minus (or negation) operator is used twice. Same

maths rules applies, ie. minus * minus= plus.

Note: However you cannot give like --2. Because -- operator can only be applied

to variables as a decrement operator (eg., i--). 2 is a constant and not a variable.

© Copyright : IT Engg Portal – www.itportal.in 525

Questions 13.

#define int char

main()

{

int i=65;

printf("sizeof(i)=%d",sizeof(i));

}

Answer:

sizeof(i)=1

Explanation:Since the #define replaces the string int by the macro char

Questions 14.

main()

{

int i=10;

i=!i>14;

Printf ("i=%d",i);

}

Answer:

i=0

Explanation:

© Copyright : IT Engg Portal – www.itportal.in 526

In the expression !i>14 , NOT (!) operator has more precedence than ‗ >‘

symbol. ! is a unary logical operator. !i (!10) is 0 (not of true is false). 0>14 is

false (zero).

Questions 15.

#include<stdio.h>

main()

{

char s[]={'a','b','c','\n','c','\0'};

char *p,*str,*str1;

p=&s[3];

str=p;

str1=s;

printf("%d",++*p + ++*str1-32);

}

Answer:77

Explanation:

p is pointing to character '\n'. str1 is pointing to character 'a' ++*p. "p is pointing

to '\n' and that is incremented by one." theASCII value of '\n' is 10, which is then

incremented to 11. The value of ++*p is 11. ++*str1, str1 is pointing to 'a' that is

incremented by 1 and it becomes 'b'. ASCII value of 'b' is 98.

Now performing (11 + 98 – 32), we get 77("M");

So we get the output 77 :: "M" (Ascii is 77).

Questions 12. main()

© Copyright : IT Engg Portal – www.itportal.in 527

{

int c=- -2;

printf("c=%d",c);

}

Answer: c=2;

Explanation:Here unary minus (or negation) operator is used twice. Same

maths rules applies, ie. minus * minus= plus.

Note: However you cannot give like --2. Because -- operator can only be applied

to variables as a decrement operator (eg., i--). 2 is a constant and not a variable.

Questions 13.

#define int char

main()

{

int i=65;

printf("sizeof(i)=%d",sizeof(i));

}

Answer:

sizeof(i)=1

Explanation:Since the #define replaces the string int by the macro char

Questions 14.

main()

{

© Copyright : IT Engg Portal – www.itportal.in 528

int i=10;

i=!i>14;

Printf ("i=%d",i);

}

Answer:

i=0

Explanation:

In the expression !i>14 , NOT (!) operator has more precedence than ‗ >‘

symbol. ! is a unary logical operator. !i (!10) is 0 (not of true is false). 0>14 is

false (zero).

Questions 15.

#include<stdio.h>

main()

{

char s[]={'a','b','c','\n','c','\0'};

char *p,*str,*str1;

p=&s[3];

str=p;

str1=s;

printf("%d",++*p + ++*str1-32);

}

Answer:77

© Copyright : IT Engg Portal – www.itportal.in 529

Explanation:

p is pointing to character '\n'. str1 is pointing to character 'a' ++*p. "p is pointing

to '\n' and that is incremented by one." theASCII value of '\n' is 10, which is then

incremented to 11. The value of ++*p is 11. ++*str1, str1 is pointing to 'a' that is

incremented by 1 and it becomes 'b'. ASCII value of 'b' is 98.

Now performing (11 + 98 – 32), we get 77("M");

So we get the output 77 :: "M" (Ascii is 77).

Questions 20. main()

{

int i=5;

printf("%d%d%d%d%d%d",i++,i--,++i,--i,i);

}

Answer:45545

Explanation:

The arguments in a function call are pushed into the stack from left to right. The

evaluation is by popping out from the stack. and the evaluation is from right to

left, hence the result.

Questions 21.

#define square(x) x*x

main()

{

int i;

© Copyright : IT Engg Portal – www.itportal.in 530

i = 64/square(4);

printf("%d",i);

}

Answer: 64

Explanation:

the macro call square(4) will substituted by 4*4 so the expression becomes i =

64/4*4 . Since / and * has equal priority the expression will be evaluated as

(64/4)*4 i.e. 16*4 = 64

Questions 22.

main()

{

char *p="hai friends",*p1;

p1=p;

while(*p!='\0') ++*p++;

printf("%s %s",p,p1);

}

Answer:

ibj!gsjfoet

Explanation:

++*p++ will be parse in the given order

*p that is value at the location currently pointed by p will be taken

++*p the retrieved value will be incremented

© Copyright : IT Engg Portal – www.itportal.in 531

when ; is encountered the location will be incremented that is p++ will be

executed

Hence, in the while loop initial value pointed by p is ‗h‘, which is changed to ‗i‘

by executing ++*p and pointer moves to point, ‗a‘ which is similarly changed to

‗b‘ and so on. Similarly blank space is converted to ‗!‘. Thus, we obtain value in

p becomes ―ibj!gsjfoet‖ and since p reaches ‗\0‘ and p1 points to p thus p1doesnot

print anything.

Questions 23.

#include <stdio.h>

#define a 10

main()

{

#define a 50

printf("%d",a);

}

Answer: 50

Explanation:The preprocessor directives can be redefined anywhere in the

program. So the most recently assigned value will be taken.

Questions 24.

#define clrscr() 100

main()

{

clrscr();

© Copyright : IT Engg Portal – www.itportal.in 532

printf("%d\n",clrscr());

}

Answer:100

Explanation:Preprocessor executes as a seperate pass before the execution of the

compiler. So textual replacement of clrscr() to 100 occurs.The input program to

compiler looks like this :

main()

{

100;

printf("%d\n",100);

}

Note:100; is an executable statement but with no action. So it doesn't give any

problem.

Questions 25. main()

{

printf("%p",main);

}

Answer: Some address will be printed.

Explanation:Function names are just addresses (just like array names are

addresses).

main() is also a function. So the address of function main will be printed. %p

in printf specifies that the argument is an address. They are printed as

hexadecimal numbers.

Questions 27

© Copyright : IT Engg Portal – www.itportal.in 533

main()

{

clrscr();

}

clrscr();

Answer:

No output/error

Explanation:

The first clrscr() occurs inside a function. So it becomes a function call. In the

second clrscr(); is a function declaration (because it is not inside any function).

Questions 28

enum colors {BLACK,BLUE,GREEN}

main()

{

printf("%d..%d..%d",BLACK,BLUE,GREEN);

return(1);

}

Answer:

0..1..2

Explanation: enum assigns numbers starting from 0, if not explicitly defined.

Questions 29 void main()

{

char far *farther,*farthest;

printf("%d..%d",sizeof(farther),sizeof(farthest));

}

Answer:

© Copyright : IT Engg Portal – www.itportal.in 534

4..2

Explanation:the second pointer is of char type and not a far pointer

Questions 30

main()

{

int i=400,j=300;

printf("%d..%d");

}

Answer:

400..300

Explanation:

printf takes the values of the first two assignments of the program.

Any number of printf's may be given. All of them take only the first two values. If

more number of assignments given in the program, then printf will take garbage

values.

Questions 31

main()

{

char *p;

p="Hello";

printf("%c\n",*&*p);

}

Answer:

H

Explanation:

* is a dereference operator & is a reference operator. They can be applied

any number of times provided it is meaningful. Here p points to the first

© Copyright : IT Engg Portal – www.itportal.in 535

character in the string "Hello". *p dereferences it and so its value is H. Again &

references it to an address and * dereferences it to the value H.

Questions 32

main()

{

int i=1;

while (i<=5)

{

printf("%d",i);

if (i>2)

goto here;

i++;

}

}

fun()

{

here:

printf("PP");

}

Answer: Compiler error: Undefined label 'here' in function main

Explanation:

Labels have functions scope, in other words The scope of the labels is limited to

functions . The label 'here' is available in function fun() Hence it is not visible in

function main.

Questions 33

main()

{

static char names[5][20]={"pascal","ada","cobol","fortran","perl"};

int i;

char *t;

t=names[3];

names[3]=names[4];

names[4]=t;

© Copyright : IT Engg Portal – www.itportal.in 536

for (i=0;i<=4;i++)

printf("%s",names[i]);

}

Answer: Compiler error: Lvalue required in function main

Explanation:

Array names are pointer constants. So it cannot be modified.

Questions 34

void main()

{

int i=5;

printf("%d",i++ + ++i);

}

Answer:

Output Cannot be predicted exactly.

Explanation:

Side effects are involved in the evaluation of i

Questions 35

void main()

{

int i=5;

printf("%d",i+++++i);

}

Questions 36

#include<stdio.h>

main()

{

int i=1,j=2;

switch(i)

{

case 1: printf("GOOD");

break;

case j: printf("BAD");

© Copyright : IT Engg Portal – www.itportal.in 537

break;

}

}

Answer:

Compiler Error: Constant expression required in function main.

Explanation:

The case statement can have only constant expressions (this implies that we

cannot use variable names directly so an error).

Note:

Enumerated types can be used in case statements.

Questions 37

main()

{

int i;

printf("%d",scanf("%d",&i)); // value 10 is given as input here

}

Answer:

1

Explanation: Scanf returns number of items successfully read and not 1/0. Here 10 is given as

input which should have been scanned successfully. So number of items read is 1.

Questions 38

#define f(g,g2) g##g2

main()

{

int var12=100;

printf("%d",f(var,12));

}

Answer:100

© Copyright : IT Engg Portal – www.itportal.in 538

Questions 39

main()

{

int i=0;

for(;i++;printf("%d",i)) ;

printf("%d",i);

}

Answer: 1

Explanation: before entering into the for loop the checking condition is

"evaluated". Here it evaluates to 0 (false) and comes out of the loop, and i is

incremented (note the semicolon after the for loop).

Questions 40

#include<stdio.h>

main()

{

char s[]={'a','b','c','\n','c','\0'};

char *p,*str,*str1;

p=&s[3];

str=p;

str1=s;

printf("%d",++*p + ++*str1-32);

}

Answer:

M

Explanation:

p is pointing to character '\n'.str1 is pointing to character 'a' ++*p meAnswer:"p

is pointing to '\n' and that is incremented by one." the ASCII value of '\n' is 10.

then it is incremented to 11. the value of ++*p is 11. ++*str1 meAnswer:"str1

is pointing to 'a' that is incremented by 1 and it becomes 'b'. ASCII value of 'b' is

98. both 11 and 98 is added and result is subtracted from 32.

i.e. (11+98-32)=77("M");

© Copyright : IT Engg Portal – www.itportal.in 539

Questions 41

#include<stdio.h>

main()

{

struct xx

{

int x=3;

char name[]="hello";

};

struct xx *s=malloc(sizeof(struct xx));

printf("%d",s->x);

printf("%s",s->name);

}

Answer:

Compiler Error

Explanation: Initialization should not be done for structure members inside the

structure declaration

Questions 42

#include<stdio.h>

main()

{

struct xx

{

int x;

struct yy

{

char s;

struct xx *p;

};

struct yy *q;

};

}

Answer:Compiler Error

Explanation: In the end of nested structure yy a member have to be declared.

© Copyright : IT Engg Portal – www.itportal.in 540

Questions 43

main()

{

extern int i;

i=20;

printf("%d",sizeof(i));

}

Answer:

Linker error: undefined symbol '_i'.

Explanation:

extern declaration specifies that the variable i is defined somewhere else. The

compiler passes the external variable to be resolved by the linker. So compiler

doesn't find an error. During linking the linker searches for the definition of i.

Since it is not found the linker flags an error.

Questions 44

main()

{

printf("%d", out);

}

int out=100;

Answer: Compiler error: undefined symbol out in function main.

Explanation:

The rule is that a variable is available for use from the point of declaration. Even

though a is a global variable, it is not available for main. Hence an error.

Questions 45

main()

{

extern out;

printf("%d", out);

}

int out=100;

© Copyright : IT Engg Portal – www.itportal.in 541

Answer:100

Explanation:

This is the correct way of writing the previous program.

Questions 46 main()

{

show();

}

void show()

{

printf("I'm the greatest");

}

Answer: Compier error: Type mismatch in redeclaration of show.

Explanation:

When the compiler sees the function show it doesn't know anything about it. So

the default return type (ie, int) is assumed. But when compiler sees the

actual definition of show mismatch occurs since it is declared as void. Hence the

error.

The solutions are as follows:

1. declare void show() in main() .

2. define show() before main().

3. declare extern void show() before the use of show().

Questions 47

main( )

{

int a[2][3][2] = {{{2,4},{7,8},{3,4}},{{2,2},{2,3},{3,4}}};

printf(―%u %u %u %d \n‖,a,*a,**a,***a);

© Copyright : IT Engg Portal – www.itportal.in 542

printf(―%u %u %u %d \n‖,a+1,*a+1,**a+1,***a+1);

}

Answer:

100, 100, 100, 2

114, 104, 102, 3

Explanation:

The given array is a 3-D one. It can also be viewed as a 1-D array.

2 4 7 8 3 4 2 2 2 3 3 4

100 102 104 106 108 110 112 114 116 118 120 122

thus, for the first printf statement a, *a, **a give address of first element . since

the indirection ***a gives the value. Hence, the first line of the output.

for the second printf a+1 increases in the third dimension thus points to value at

114, *a+1 increments in second dimension thus points to 104, **a +1 increments

the first dimension thus points to 102 and ***a+1 first gets the value at first

location and then increments it by 1. Hence, the output.

Questions 48

main( )

{

int a[ ] = {10,20,30,40,50},j,*p;

for(j=0; j<5; j++)

{

printf(―%d‖ ,*a);

a++;

}

© Copyright : IT Engg Portal – www.itportal.in 543

p = a;

for(j=0; j<5; j++)

{

printf(―%d ‖ ,*p);

p++;

}

}

Answer: Compiler error: lvalue required.

Explanation:

Error is in line with statement a++. The operand must be an lvalue and may be of

any of scalar type for the any operator, array name only when subscripted is an

lvalue. Simply array name is a non-modifiable lvalue.

Questions 49

main( ){

static int a[ ] = {0,1,2,3,4};

int *p[ ] = {a,a+1,a+2,a+3,a+4};

int **ptr = p;

ptr++;

printf(―\n %d %d %d‖, ptr-p, *ptr-a, **ptr);

*ptr++;

printf(―\n %d %d %d‖, ptr-p, *ptr-a, **ptr);

*++ptr;

printf(―\n %d %d %d‖, ptr-p, *ptr-a, **ptr);

++*ptr;

printf(―\n %d %d %d‖, ptr-p, *ptr-a, **ptr);

}

Answer:

111

222

333

344

© Copyright : IT Engg Portal – www.itportal.in 544

Explanation:

Let us consider the array and the two pointers with some address

a

0 1 2 3 4

100 102 104 106 108

p

100 102 104 106 108

1000 1002 1004 1006 1008

ptr

1000

2000

After execution of the instruction ptr++ value in ptr becomes 1002, if scaling

factor for integer is 2 bytes. Now ptr – p is value in ptr – starting location of array

p, (1002 – 1000) / (scaling factor) = 1, *ptr – a = value at address pointed by ptr

– starting value of array a, 1002 has a value 102 so the value is (102 –

100)/(scaling factor) = 1, **ptr is the value stored in the location pointed by the

pointer of ptr = value pointed by value pointed by 1002 = value pointed by 102 =

1. Hence the output of the firs printf is 1, 1, 1.

After execution of *ptr++ increments value of the value in ptr by scaling factor,

so it becomes1004. Hence, the outputs for the second printf are ptr – p = 2, *ptr –

a = 2, **ptr = 2.

After execution of *++ptr increments value of the value in ptr by scaling factor,

so it becomes1004. Hence, the outputs for the third printf are ptr – p = 3, *ptr – a

= 3, **ptr = 3.

After execution of ++*ptr value in ptr remains the same, the value pointed by the

value is incremented by the scaling factor. So the value in array p at location 1006

© Copyright : IT Engg Portal – www.itportal.in 545

changes from 106 10 108,. Hence, the outputs for the fourth printf are ptr – p =

1006 – 1000 = 3, *ptr – a = 108 – 100 = 4, **ptr = 4.

Questions 50

main( )

{

char *q;

int j;

for (j=0; j<3; j++) scanf(―%s‖ ,(q+j));

for (j=0; j<3; j++) printf(―%c‖ ,*(q+j));

for (j=0; j<3; j++) printf(―%s‖ ,(q+j));

}

Explanation:

Here we have only one pointer to type char and since we take input in the same

pointer thus we keep writing over in the same location, each time shifting the

pointer value by 1. Suppose the inputs are MOUSE, TRACK and VIRTUAL.

Then for the first input suppose the pointer starts at location 100 then the input

one is stored as

M O U S E \0

When the second input is given the pointer is incremented as j value becomes 1,

so the input is filled in memory starting from 101.

M T R A C K \0

The third input starts filling from the location 102

M T V I R T U A L \0

This is the final value stored .

The first printf prints the values at the position q, q+1 and q+2 = M T V

The second printf prints three strings starting from locations q, q+1, q+2

i.e MTVIRTUAL, TVIRTUAL and VIRTUAL.

© Copyright : IT Engg Portal – www.itportal.in 546

Questions 51 main( )

{

void *vp;

char ch = ‗g‘, *cp = ―goofy‖;

int j = 20;

vp = &ch;

printf(―%c‖, *(char *)vp);

vp = &j;

printf(―%d‖,*(int *)vp);

vp = cp;

printf(―%s‖,(char *)vp + 3);

}

Answer:

g20fy

Explanation:

Since a void pointer is used it can be type casted to any other type pointer. vp =

&ch stores address of char ch and the next statement prints the value stored in vp

after type casting it to the proper data type pointer. the output is ‗g‘. Similarly the

output from second printf is ‗20‘. The third printf statement type casts it to print

the string from the 4th value hence the output is ‗fy‘.

Questions 52

main ( )

{

static char *s[ ] = {―black‖, ―white‖, ―yellow‖, ―violet‖};

© Copyright : IT Engg Portal – www.itportal.in 547

char **ptr[ ] = {s+3, s+2, s+1, s}, ***p;

p = ptr;

**++p;

printf(―%s‖,*--*++p + 3);

}

Answer:ck

Explanation:

In this problem we have an array of char pointers pointing to start of 4 strings.

Then we have ptr which is a pointer to a pointer of type char and a variable p

which is a pointer to a pointer to a pointer of type char. p hold the initial value of

ptr, i.e. p = s+3. The next statement increment value in p by 1 , thus now value of

p = s+2. In the printf statement the expression is evaluated *++p causes gets

value s+1 then the pre decrement is executed and we get s+1 – 1 = s . the

indirection operator now gets the value from the array of s and adds 3 to the

starting address. The string is printed starting from this position. Thus, the output

is ‗ck‘.

Questions 53

main()

{

int i, n;

char *x = ―girl‖;

n = strlen(x);

*x = x[n];

for(i=0; i<n; ++i)

{

printf(―%s\n‖,x);

x++;

}

}

Answer:

(blank space)

irl

© Copyright : IT Engg Portal – www.itportal.in 548

rl

l

Explanation:

Here a string (a pointer to char) is initialized with a value ―girl‖. The strlen

function returns the length of the string, thus n has a value 4. The next statement

assigns value at the nth location (‗\0‘) to the first location. Now the string

becomes ―\0irl‖ . Now the printf statement prints the string after each iteration

it increments it starting position. Loop starts from 0 to 4. The first time x[0] =

‗\0‘ hence it prints nothing and pointer value is incremented. The second time

it prints from x[1] i.e ―irl‖ and the third time it prints ―rl‖ and the last time

it prints ―l‖ and the loop terminates.

Questions 54 int i,j;

for(i=0;i<=10;i++)

{

j+=5;

assert(i<5);

}

Answer: Runtime error: Abnormal program termination. assert failed (i<5), <file

name>,<line number>

Explanation:

asserts are used during debugging to make sure that certain conditions are

satisfied. If assertion fails, the program will terminate reporting the same. After

debugging use,

#undef NDEBUG

and this will disable all the assertions from the source code. Assertion

is a good debugging tool to make use of.

Questions 55

© Copyright : IT Engg Portal – www.itportal.in 549

main()

{

int i=-1;

+i;

printf("i = %d, +i = %d \n",i,+i);

}

Answer:

i = -1, +i = -1

Explanation:

Unary + is the only dummy operator in C. Where-ever it comes you can just

ignore it just because it has no effect in the expressions (hence the name dummy

operator).

Questions 56 : What are the files which are automatically opened when a C file

is executed?

Answer: stdin, stdout, stderr (standard input,standard output,standard error).

Questions 57: what will be the position of the file marker?

a: fseek(ptr,0,SEEK_SET);

b: fseek(ptr,0,SEEK_CUR);

Answer :

a: The SEEK_SET sets the file position marker to the starting of the file.

b: The SEEK_CUR sets the file position marker to the current position

of the file.

Questions 58: main()

{

char name[10],s[12];

© Copyright : IT Engg Portal – www.itportal.in 550

scanf(" \"%[^\"]\"",s);

}

How scanf will execute?

Answer:First it checks for the leading white space and discards it.Then it

matches with a quotation mark and then it reads all character upto another

quotation mark.

Questions 59 What is the problem with the following code segment?

while ((fgets(receiving array,50,file_ptr)) != EOF)

;

Answer & Explanation: fgets returns a pointer. So the correct end of file check

is checking for != NULL.

Questions 60 main()

{

main();

}

Answer: Runtime error : Stack overflow.

Explanation: main function calls itself again and again. Each time the function is

called its return address is stored in the callstack. Since there is no condition to

terminate the function call, the call stack overflows at runtime. So it terminates

the program and results in an error.

Questions 61

main()

{

char *cptr,c;

void *vptr,v;

c=10; v=0;

cptr=&c; vptr=&v;

© Copyright : IT Engg Portal – www.itportal.in 551

printf("%c%v",c,v);

}

Answer:

Compiler error (at line number 4): size of v is Unknown.

Explanation: You can create a variable of type void * but not of type void, since

void is an empty type. In the second line you are creating variable vptr of type

void * and v of type void hence an error.

Questions 62

main()

{

char *str1="abcd";

char str2[]="abcd";

printf("%d %d %d",sizeof(str1),sizeof(str2),sizeof("abcd"));

}

Answer:

2 5 5

Explanation: In first sizeof, str1 is a character pointer so it gives you the size of

the pointer variable. In second sizeof the name str2 indicates the name of the

array whose size is 5 (including the '\0' termination character). The third sizeof is

similar to the second one.

Questions 63

main()

{

char not;

not=!2;

printf("%d",not);

}

Answer:

0

© Copyright : IT Engg Portal – www.itportal.in 552

Explanation:

! is a logical operator. In C the value 0 is considered to be the boolean value

FALSE, and any non-zero value is considered to be the boolean value TRUE.

Here 2 is a non-zero value so TRUE. !TRUE is FALSE (0) so it prints 0.

Questions 64

#define FALSE -1

#define TRUE 1

#define NULL 0

main() {

if(NULL)

puts("NULL");

else if(FALSE)

puts("TRUE");

else

puts("FALSE");

}

Answer:TRUE

Explanation:The input program to the compiler after processing by the

preprocessor is,

main(){

if(0)

puts("NULL");

else if(-1)

puts("TRUE");

else

puts("FALSE");

}

Preprocessor doesn't replace the values given inside the double quotes. The check

by if condition is boolean value false so it goes to else. In second if -1 is boolean

value true hence "TRUE" is printed.

© Copyright : IT Engg Portal – www.itportal.in 553

Questions 65

main()

{

int k=1;

printf("%d==1 is ""%s",k,k==1?"TRUE":"FALSE");

}

Answer:

1==1 is TRUE

Explanation:

When two strings are placed together (or separated by white-space) they are

concatenated (this is called as "stringization"operation). So the string is as if it is

given as "%d==1 is %s". The conditional operator( ?: ) evaluates to "TRUE".

Questions 66

main()

{

int y;

scanf("%d",&y); // input given is 2000

if( (y%4==0 && y%100 != 0) || y%100 == 0 )

printf("%d is a leap year");

else

printf("%d is not a leap year");

}

Answer:

2000 is a leap year

Explanation:

An ordinary program to check if leap year or not.

Questions 67

#define max 5

#define int arr1[max]

© Copyright : IT Engg Portal – www.itportal.in 554

main()

{

typedef char arr2[max];

arr1 list={0,1,2,3,4};

arr2 name="name";

printf("%d %s",list[0],name);

}

Answer:

Compiler error (in the line arr1 list = {0,1,2,3,4})

Explanation:arr2 is declared of type array of size 5 of characters. So it can be

used to declare the variable name of the type arr2. But it is not the case of arr1.

Hence an error.

Rule of Thumb:

#defines are used for textual replacement whereas typedefs are used for declaring

new types.

Questions 68

int i=10;

main()

{

extern int i;

{

int i=20;

{

const volatile unsigned i=30;

printf("%d",i);

}

printf("%d",i);

}

printf("%d",i);

}

Answer:

30,20,10

Explanation:

'{' introduces new block and thus new scope. In the innermost block i is declared

© Copyright : IT Engg Portal – www.itportal.in 555

as,

const volatile unsigned

which is a valid declaration. i is assumed of type int. So printf prints 30. In the

next block, i has value 20 and so printf prints 20. In the outermost block, i is

declared as extern, so no storage space is allocated for it. After compilation is

over the linker resolves it to global variable i (since it is the only variable visible

there). So it prints i's value as 10.

Questions 69

main()

{

int *j;

{

int i=10;

j=&i;

}

printf("%d",*j);

}

Answer:

10

Explanation:

The variable i is a block level variable and the visibility is inside that block only.

But the lifetime of i is lifetime of the function so it lives upto the exit of main

function. Since the i is still allocated space, *j prints the value stored in i since j

points i.

Questions 70

main()

{

int i=-1;

-i;

printf("i = %d, -i = %d \n",i,-i);

}

Answer:

i = -1, -i = 1

© Copyright : IT Engg Portal – www.itportal.in 556

Explanation:

-i is executed and this execution doesn't affect the value of i. In printf first you

just print the value of i. After that the value of the expression -i = -(-1) is printed.

Questions 71

#include<stdio.h>

main()

{

const int i=4;

float j;

j = ++i;

printf("%d %f", i,++j);

}

Answer:Compiler error

Explanation: i is a constant. you cannot change the value of constant

Questions 72

#include<stdio.h>

main()

{

int a[2][2][2] = { {10,2,3,4}, {5,6,7,8} };

int *p,*q;

p=&a[2][2][2];

*q=***a;

printf("%d..%d",*p,*q);

}

Answer: garbagevalue..1

Explanation:

p=&a[2][2][2] you declare only two 2D arrays. but you are trying to access the

third 2D(which you are not declared) it will print garbage values.

*q=***a starting address of a is assigned integer pointer. now q

is pointing to starting address of a.if you print *q meAnswer:it will print

first element of 3D array.

© Copyright : IT Engg Portal – www.itportal.in 557

Questions 73

#include<stdio.h>

main()

{

register i=5;

char j[]= "hello";

printf("%s %d",j,i);

}

Answer:

hello 5

Explanation:

if you declare i as register compiler will treat it as ordinary integer and it will

take integer value. i value may be stored either in register or in memory.

Questions 74

main()

{

int i=5,j=6,z;

printf("%d",i+++j);

}

Answer:

11

Explanation: the expression i+++j is treated as (i++ + j)

Questions 76

struct aaa{

struct aaa *prev;

int i;

struct aaa *next;

};

main()

{

struct aaa abc,def,ghi,jkl;

int x=100;

abc.i=0;abc.prev=&jkl;

abc.next=&def;

© Copyright : IT Engg Portal – www.itportal.in 558

def.i=1;def.prev=&abc;def.next=&ghi;

ghi.i=2;ghi.prev=&def;

ghi.next=&jkl;

jkl.i=3;jkl.prev=&ghi;jkl.next=&abc;

x=abc.next->next->prev->next->i;

printf("%d",x);

}

Answer:

2

Explanation:

above all statements form a double circular linked list;abc.next->next->prev-

>next->i this one points to "ghi" node the value of at particular node is 2.

Questions 77

struct point

{

int x;

int y;

};

struct point origin,*pp;

main()

{

pp=&origin;

printf("origin is(%d%d)\n",(*pp).x,(*pp).y);

printf("origin is (%d%d)\n",pp->x,pp->y);

}

Answer:

origin is(0,0)

origin is(0,0)

Explanation: pp is a pointer to structure. we can access the elements of

the structure either with arrow mark or with indirection operator.

Note: Since structure point is globally declared x & y are initialized as zeroes

© Copyright : IT Engg Portal – www.itportal.in 559

Questions 78

main()

{

int i=_l_abc(10);

printf("%d\n",--i);

}

int _l_abc(int i)

{

return(i++);

}

Answer:

9

Explanation: return(i++) it will first return i and then increments. i.e. 10 will be returned.

Questions 79

main()

{

char *p;

int *q;

long *r;

p=q=r=0;

p++;

q++;

r++;

printf("%p...%p...%p",p,q,r);

}

Answer:

0001...0002...0004

Explanation:++ operator when applied to pointers increments address according

to their corresponding data-types.

© Copyright : IT Engg Portal – www.itportal.in 560

Questions 80

main()

{

char c=' ',x,convert(z);

getc(c);

if((c>='a') && (c<='z'))

x=convert(c);

printf("%c",x);

}

convert(z)

{

return z-32;

}

Answer:

Compiler error

Explanation:

declaration of convert and format of getc() are wrong.

Questions 81

main(int argc, char **argv)

{

printf("enter the character");

getchar();

sum(argv[1],argv[2]);

}

sum(num1,num2)

int num1,num2;

{

return num1+num2;

}

Answer:

Compiler error.

© Copyright : IT Engg Portal – www.itportal.in 561

Explanation:

argv[1] & argv[2] are strings. They are passed to the function sum without

converting it to integer values.

Questions 82

# include <stdio.h>

int one_d[]={1,2,3};

main()

{

int *ptr;

ptr=one_d;

ptr+=3;

printf("%d",*ptr);

}

Answer:

garbage value

Explanation: ptr pointer is pointing to out of the array range of one_d.

Questions 83

# include<stdio.h>

aaa() {

printf("hi");

}

bbb(){

printf("hello");

}

ccc(){

printf("bye");

}

main()

{

int (*ptr[3])();

ptr[0]=aaa;

ptr[1]=bbb;

ptr[2]=ccc;

ptr[2]();

© Copyright : IT Engg Portal – www.itportal.in 562

}

Answer:

bye

Explanation: ptr is array of pointers to functions of return type int.ptr[0] is assigned to address

of the function aaa. Similarly ptr[1] and ptr[2] for bbb and ccc respectively.

ptr[2]() is in effect of writing ccc(), since ptr[2] points to ccc.

Questions 85

#include<stdio.h>

main()

{

FILE *ptr;

char i;

ptr=fopen("zzz.c","r");

while((i=fgetch(ptr))!=EOF)

printf("%c",i);

}

Answer:

contents of zzz.c followed by an infinite loop

Explanation:

The condition is checked against EOF, it should be checked against NULL.

Questions 86

main()

{

int i =0;j=0;

if(i && j++)

printf("%d..%d",i++,j);

printf("%d..%d,i,j);

}

Answer:

0..0

© Copyright : IT Engg Portal – www.itportal.in 563

Explanation:

The value of i is 0. Since this information is enough to determine the truth value

of the boolean expression. So the statement following the if statement is not

executed. The values of i and j remain unchanged and get printed.

Questions 87

main()

{

int i;

i = abc();

printf("%d",i);

}

abc()

{

_AX = 1000;

}

Answer:

1000

Explanation:

Normally the return value from the function is through the information from the

accumulator. Here _AH is the pseudo global variable denoting the accumulator.

Hence, the value of the accumulator is set 1000 so the function returns value

1000.

Questions 88

int i;

main(){

int t;

for ( t=4;scanf("%d",&i)-t;printf("%d\n",i))

printf("%d--",t--);

}

// If the inputs are 0,1,2,3 find the o/p

Answer:

4--0

3--1

© Copyright : IT Engg Portal – www.itportal.in 564

2--2

Explanation:Let us assume some x= scanf("%d",&i)-t the values during

execution will be,

t i x

4 0 -4

3 1 -2

2 2 0

Questions 89

main(){

int a= 0;int b = 20;char x =1;char y =10;

if(a,b,x,y)

printf("hello");

}

Answer:

hello

Explanation:

The comma operator has associatively from left to right. Only the rightmost value

is returned and the other values are evaluated and ignored. Thus the value of last

variable y is returned to check in if. Since it is a non zero value if becomes true

so, "hello" will be printed.

Questions 90

main(){

unsigned int i;

for(i=1;i>-2;i--)

printf("c aptitude");

}

Explanation: i is an unsigned integer. It is compared with a signed value. Since the both types

doesn't match, signed is promoted to unsigned value. The unsigned equivalent of -

2 is a huge value so condition becomes false and control comes out of the loop.

© Copyright : IT Engg Portal – www.itportal.in 565

Questions 91

In the following pgm add a stmt in the function fun such that the address of 'a'

gets stored in 'j'.

main(){

int * j;

void fun(int **);

fun(&j);

}

void fun(int **k) {

int a =0;

/* add a stmt here*/

}

Answer:

*k = &a

Explanation:

The argument of the function is a pointer to a pointer.

Questions 92:

What are the following notations of defining functions known as?

int abc(int a,float b)

{

/* some code */

}

ii. int abc(a,b)

int a; float b;

{

/* some code*/

}

Answer:

i. ANSI C notation

ii. Kernighan & Ritche notation

Questions 93

main()

© Copyright : IT Engg Portal – www.itportal.in 566

{

char *p;

p="%d\n";

p++;

p++;

printf(p-2,300);

}

Answer:

300

Explanation:

The pointer points to % since it is incremented twice and again decremented by 2,

it points to '%d\n' and 300 is printed.

Questions 94

main(){

char a[100];

a[0]='a';a[1]]='b';a[2]='c';a[4]='d';

abc(a);

}

abc(char a[]){

a++;

printf("%c",*a);

a++;

printf("%c",*a);

}

Explanation:

The base address is modified only in function and as a result a points to 'b' then

after incrementing to 'c' so bc will beprinted.

Questions 95

func(a,b)

int a,b;

{

return( a= (a==b) );

}

main()

© Copyright : IT Engg Portal – www.itportal.in 567

{

int process(),func();

printf("The value of process is %d !\n ",process(func,3,6));

}

process(pf,val1,val2)

int (*pf) ();

int val1,val2;

{

return((*pf) (val1,val2));

}

Answer:

The value if process is 0 !

Explanation:The function 'process' has 3 parameters - 1, a pointer to

another function 2 and 3, integers. When this functionis invoked from main, the

following substitutions for formal parameters take place: func for pf, 3 for val1

and 6 for val2. Thisfunction returns the result of the operation performed

by the function 'func'. The function func has two integer parameters. The

formal parameters are substituted as 3 for a and 6 for b. since 3 is not equal to 6,

a==b returns 0. therefore the functionreturns 0 which in turn is returned by the

function 'process'.

Questions 96

void main()

{

static int i=5;

if(--i){

main();

printf("%d ",i);

}

}

Answer:

0 0 0 0

Explanation:

The variable "I" is declared as static, hence memory for I will be allocated for

© Copyright : IT Engg Portal – www.itportal.in 568

only once, as it encounters the statement. Thefunction main() will be called

recursively unless I becomes equal to 0, and since main() is recursively called, so

the value of static I ie., 0 will be printed every time the control is returned.

Questions 97

void main()

{

int k=ret(sizeof(float));

printf("\n here value is %d",++k);

}

int ret(int ret)

{

ret += 2.5;

return(ret);

}

Answer:

Here value is 7

Explanation:

The int ret(int ret), ie., the function name and the argument name can be the

same. Firstly, the function ret() is called in which the sizeof(float) ie., 4 is

passed, after the first expression the value in ret will be 6, as ret is integer hence

the value stored in ret will have implicit type conversion from float to int. The ret

is returned in main() it is printed after and preincrement.

Questions 98

void main()

{

char a[]="12345\0";

int i=strlen(a);

printf("here in 3 %d\n",++i);

}

Answer:

here in 3 6

© Copyright : IT Engg Portal – www.itportal.in 569

Explanation:The char array 'a' will hold the initialized string, whose length will

be counted from 0 till the null character. Hence the 'I' will hold the value equal to

5, after the pre-increment in the printf statement, the 6 will be printed.

Questions 99 void main()

{

unsigned giveit=-1;

int gotit;

printf("%u ",++giveit);

printf("%u \n",gotit=--giveit);

}

Answer:

0 65535

100) void main()

{

int i;

char a[]="\0";

if(printf("%s\n",a))

printf("Ok here \n");

else

printf("Forget it\n");

}

Answer:

Ok here

Explanation: Printf will return how many characters does it print. Hence printing a null

character returns 1 which makes the if statement true, thus "Ok here" is printed.

Questions 101

void main()

{

void *v;

int integer=2;

int *i=&integer;

© Copyright : IT Engg Portal – www.itportal.in 570

v=i;

printf("%d",(int*)*v);

}

Answer:

Compiler Error. We cannot apply indirection on type void*.

Explanation:

Void pointer is a generic pointer type. No pointer arithmetic can be done on it.

Void pointers are normally used for,

1. Passing generic pointers to functions and returning such pointers.

2. As a intermediate pointer type.

3. Used when the exact pointer type will be known at a later point of time.

Questions 102

void main()

{

int i=i++,j=j++,k=k++;

printf(―%d%d%d‖,i,j,k);

}

Answer:

Garbage values.

Explanation:

An identifier is available to use in program code from the point of its declaration.

So expressions such as i = i++ are valid statements. The i, j and k are automatic

variables and so they contain some garbage value. Garbage in is garbage out

(GIGO).

Questions 103

void main()

{

static int i=i++, j=j++, k=k++;

© Copyright : IT Engg Portal – www.itportal.in 571

printf(―i = %d j = %d k = %d‖, i, j, k);

}

Answer:

i = 1 j = 1 k = 1

Explanation:

Since static variables are initialized to zero by default.

Questions 104

void main()

{

while(1){

if(printf("%d",printf("%d")))

break;

else

continue;

}

}

Answer:

Garbage values

Explanation:

The inner printf executes first to print some garbage value. The printf returns no

of characters printed and this value also cannot be predicted. Still the

outer printf prints something and so returns a non-zero value. So it encounters

the break statement and comes out of the while statement.

Questions 104

main()

{

unsigned int i=10;

while(i-->=0)

printf("%u ",i);

© Copyright : IT Engg Portal – www.itportal.in 572

}

Answer:

10 9 8 7 6 5 4 3 2 1 0 65535 65534…..

Explanation:

Since i is an unsigned integer it can never become negative. So the expression i--

>=0 will always be true, leading to aninfinite loop.

Questions 105

#include<conio.h>

main()

{

int x,y=2,z,a;

if(x=y%2) z=2;

a=2;

printf("%d %d ",z,x);

}

Answer:

Garbage-value 0

Explanation:

The value of y%2 is 0. This value is assigned to x. The condition reduces to if (x)

or in other words if(0) and so z goes uninitialized.

Thumb Rule: Check all control paths to write bug free code.

Questions 106

main()

{

int a[10];

printf("%d",*a+1-*a+3);

}

Answer:

4

Explanation:

*a and -*a cancels out. The result is as simple as 1 + 3 = 4 !

© Copyright : IT Engg Portal – www.itportal.in 573

Questions 107

#define prod(a,b) a*b

main()

{

int x=3,y=4;

printf("%d",prod(x+2,y-1));

}

Answer:

10

Explanation:

The macro expands and evaluates to as:

x+2*y-1 => x+(2*y)-1 => 10

Questions 108

main()

{

unsigned int i=65000;

while(i++!=0);

printf("%d",i);

}

Answer:

1

Explanation:

Note the semicolon after the while statement. When the value of i becomes 0 it

comes out of while loop. Due to post-increment on i the value of i while printing

is 1.

Questions 109

main()

{

int i=0;

while(+(+i--)!=0)

i-=i++;

printf("%d",i);

}

© Copyright : IT Engg Portal – www.itportal.in 574

Answer:

-1

Explanation:

Unary + is the only dummy operator in C. So it has no effect on the expression

and now the while loop is, while(i--!=0) which is false and so breaks out of

while loop. The value –1 is printed due to the post-decrement operator.

Questions 110 main()

{

float f=5,g=10;

enum{i=10,j=20,k=50};

printf("%d\n",++k);

printf("%f\n",f<<2);

printf("%lf\n",f%g);

printf("%lf\n",fmod(f,g));

}

Answer:

Line no 5: Error: Lvalue required

Line no 6: Cannot apply leftshift to float

Line no 7: Cannot apply mod to float

Explanation:

Enumeration constants cannot be modified, so you cannot apply ++.Bit-wise

operators and % operators cannot be applied on float values. fmod() is to find the

modulus values for floats as % operator is for ints.

Questions 110

main()

{

int i=10;

void pascal f(int,int,int);

f(i++,i++,i++);

printf(" %d",i);

}

© Copyright : IT Engg Portal – www.itportal.in 575

void pascal f(integer :i,integer:j,integer :k)

{

write(i,j,k);

}

Answer:

Compiler error: unknown type integer

Compiler error: undeclared function write

Explanation:

Pascal keyword doesn‘t mean that pascal code can be used. It means that the

function follows Pascal argument passing mechanism in calling the functions.

Questions 111

void pascal f(int i,int j,int k)

{

printf(―%d %d %d‖,i, j, k);

}

void cdecl f(int i,int j,int k)

{

printf(―%d %d %d‖,i, j, k);

}

main()

{

int i=10;

f(i++,i++,i++);

printf(" %d\n",i);

i=10;

f(i++,i++,i++);

printf(" %d",i);

}

Answer:

10 11 12 13

12 11 10 13

Explanation:

Pascal argument passing mechanism forces the arguments to be called from left to

© Copyright : IT Engg Portal – www.itportal.in 576

right. cdecl is the normal C argument passing mechanism where the arguments

are passed from right to left.

Questions 112. What is the output of the program given below

main()

{

signed char i=0;

for(;i>=0;i++) ;

printf("%d\n",i);

}

Answer

-128

Explanation

Notice the semicolon at the end of the for loop. THe initial value of the i is set to

0. The inner loop executes to increment the value from 0 to 127 (the positive

range of char) and then it rotates to the negative value of -128. The condition in

the for loop fails and so comes out of the for loop. It prints the current value of i

that is -128.

Questions 113

main()

{

unsigned char i=0;

for(;i>=0;i++) ;

printf("%d\n",i);

}

Answer

infinite loop

Explanation

The difference between the previous question and this one is that the char is

declared to be unsigned. So the i++ can never yield negative value and i>=0 never

becomes false so that it can come out of the for loop.

© Copyright : IT Engg Portal – www.itportal.in 577

Questions 114 main()

{

char i=0;

for(;i>=0;i++) ;

printf("%d\n",i);

}

Answer:Behavior is implementation dependent.

Explanation:The detail if the char is signed/unsigned by default is

implementation dependent. If the implementation treats the char to be signed by

default the program will print –128 and terminate. On the other hand if it

considers char to be unsigned by default, it goes to infinite loop.

Rule:

You can write programs that have implementation dependent behavior. But dont

write programs that depend on such behavior.

Questions 115 Is the following statement a declaration/definition. Find what

does it mean?

int (*x)[10];

Answer Definition.

x is a pointer to array of(size 10) integers.

Apply clock-wise rule to find the meaning of this definition.

Questions 116. What is the output for the program given below

typedef enum errorType{warning, error, exception,}error;

main()

{

error g1;

g1=1;

printf("%d",g1);

© Copyright : IT Engg Portal – www.itportal.in 578

}

Answer Compiler error: Multiple declaration for error

Explanation The name error is used in the two meanings. One means that it is a enumerator

constant with value 1. The another use is that it is a type name (due to typedef)

for enum errorType. Given a situation the compiler cannot distinguish the

meaning of error to know in what sense the error is used:

error g1;

g1=error;

// which error it refers in each case?

When the compiler can distinguish between usages then it will not issue error (in

pure technical terms, names can only be overloaded in different namespaces).

Note: the extra comma in the declaration,

enum errorType{warning, error, exception,}

is not an error. An extra comma is valid and is provided just for programmer‘s

convenience.

Questions 117

typedef struct error{int warning, error, exception;}error;

main()

{

error g1;

g1.error =1;

printf("%d",g1.error);

}

Answer 1

Explanation The three usages of name errors can be distinguishable by the compiler at any

instance, so valid (they are in different namespaces).

Typedef struct error{int warning, error, exception;}error;

© Copyright : IT Engg Portal – www.itportal.in 579

This error can be used only by preceding the error by struct kayword as in:

struct error someError;

typedef struct error{int warning, error, exception;}error;

This can be used only after . (dot) or -> (arrow) operator preceded by the variable

name as in :

g1.error =1;

printf("%d",g1.error);

typedef struct error{int warning, error, exception;}error;

This can be used to define variables without using the preceding struct keyword

as in:

error g1;

Since the compiler can perfectly distinguish between these three usages, it is

perfectly legal and valid.

Note This code is given here to just explain the concept behind. In real programming

don‘t use such overloading of names. It reduces the readability of the code.

Possible doesn‘t mean that we should use it!

Questions 118

#ifdef something

int some=0;

#endif

main()

{

int thing = 0;

printf("%d %d\n", some ,thing);

}

Answer: Compiler error : undefined symbol some

© Copyright : IT Engg Portal – www.itportal.in 580

Explanation: This is a very simple example for conditional compilation. The name something

is not already known to the compiler making the declaration

int some = 0;

effectively removed from the source code.

Questions 119

#if something == 0

int some=0;

#endif

main()

{

int thing = 0;

printf("%d %d\n", some ,thing);

}

Answer

0 0

Explanation This code is to show that preprocessor expressions are not the same as the

ordinary expressions. If a name is not known the preprocessor treats it to be equal

to zero.

Questions 120.

What is the output for the following program

main()

{

int arr2D[3][3];

printf("%d\n", ((arr2D==* arr2D)&&(* arr2D == arr2D[0])) );

}

Answer

1

© Copyright : IT Engg Portal – www.itportal.in 581

Explanation This is due to the close relation between the arrays and pointers. N dimensional

arrays are made up of (N-1) dimensional arrays. arr2D is made up of a

3 single arrays that contains 3 integers each .The name arr2D refers to the

beginning of all the 3 arrays. *arr2D refers to the start of the first 1D array (of 3

integers) that is the same address as arr2D. So the expression(arr2D == *arr2D) is

true (1). Similarly, *arr2D is nothing but *(arr2D + 0), adding a zero doesn‘t

change the value/meaning. Again arr2D[0] is the another way of telling *(arr2D +

0). So the expression (*(arr2D + 0) == arr2D[0]) is true (1). Since both parts

of the expression evaluates to true the result is true(1) and the same is printed.

Questions 121

void main()

{

if(~0 == (unsigned int)-1)

printf(―You can answer this if you know how values are represented in

memory‖);

}

Answer

You can answer this if you know how values are represented in memory

Explanation

~ (tilde operator or bit-wise negation operator) operates on 0 to produce all ones

to fill the space for an integer. –1 is represented in unsigned value as all 1‘s and

so both are equal.

Questions 122

int swap(int *a,int *b)

{

*a=*a+*b;*b=*a-*b;*a=*a-*b;

}

main()

{

int x=10,y=20;

swap(&x,&y);

printf("x= %d y = %d\n",x,y);

}

© Copyright : IT Engg Portal – www.itportal.in 582

Answer

x = 20 y = 10

Explanation

This is one way of swapping two values. Simple checking will

help understand this.

Questions 123

main()

{

char *p = ―ayqm‖;

printf(―%c‖,++*(p++));

}

Answer:

b

Questions 124

main()

{

int i=5;

printf("%d",++i++);

}

Answer:

Compiler error: Lvalue required in function main

Explanation:

++i yields an rvalue. For postfix ++ to operate an lvalue is required.

Questions 125

main()

{

char *p = ―ayqm‖;

char c;

c = ++*p++;

printf(―%c‖,c);

}

Answer:

b

© Copyright : IT Engg Portal – www.itportal.in 583

Explanation:

There is no difference between the expression ++*(p++) and ++*p++. Parenthesis

just works as a visual clue for the reader to see which expression is first

evaluated.

Questions 126

int aaa() {printf(―Hi‖);}

int bbb(){printf(―hello‖);}

iny ccc(){printf(―bye‖);}

main()

{

int ( * ptr[3]) ();

ptr[0] = aaa;

ptr[1] = bbb;

ptr[2] =ccc;

ptr[2]();

}

Answer:

bye

Explanation: int (* ptr[3])() says that ptr is an array of pointers to functions that takes no

arguments and returns the type int. By the assignment ptr[0] = aaa; it means that

the first function pointer in the array is initialized with the address of the function

aaa. Similarly, the other two array elements also get initialized with the addresses

of the functions bbb and ccc. Since ptr[2]contains the address of the function

ccc, the call to the function ptr[2]() is same as calling ccc(). So it results

in printing "bye".

Questions 127

main()

{

int i=5;

© Copyright : IT Engg Portal – www.itportal.in 584

printf(―%d‖,i=++i ==6);

}

Answer:

1

Explanation:

The expression can be treated as i = (++i==6), because == is of higher precedence

than = operator. In the inner expression, ++i is equal to 6 yielding true(1). Hence

the result.

Questions 128

main()

{

char p[ ]="%d\n";

p[1] = 'c';

printf(p,65);

}

Answer:

A

Explanation:

Due to the assignment p[1] = ‗c‘ the string becomes, ―%c\n‖. Since this string

becomes the format string for printf and ASCII value of 65 is ‗A‘, the same gets

printed.

Questions 129

void ( * abc( int, void ( *def) () ) ) ();

Answer::

abc is a ptr to a function which takes 2 parameters .(a).

an integer variable.(b). a ptrto a funtion which returns void. the return type of

the function is void.

Explanation:

Apply the clock-wise rule to find the result.

© Copyright : IT Engg Portal – www.itportal.in 585

Questions 130

main()

{

while (strcmp(―some‖,‖some\0‖))

printf(―Strings are not equal\n‖);

}

Answer:

No output

Explanation:

Ending the string constant with \0 explicitly makes no difference. So ―some‖ and

―some\0‖ are equivalent. So, strcmp returns 0 (false) hence breaking out of the

while loop.

Questions 131

main()

{

char str1[] = {‗s‘,‘o‘,‘m‘,‘e‘};

char str2[] = {‗s‘,‘o‘,‘m‘,‘e‘,‘\0‘};

while (strcmp(str1,str2))

printf(―Strings are not equal\n‖);

}

Answer: ―Strings are not equal‖

―Strings are not equal‖

….

Explanation: If a string constant is initialized explicitly with characters, ‗\0‘ is not

appended automatically to the string. Since str1 doesn‘t have null termination, it

treats whatever the values that are in the following positions as part of the string

until it randomly reaches a ‗\0‘. So str1 and str2 are not the same, hence the

result.

Questions 132

main()

© Copyright : IT Engg Portal – www.itportal.in 586

{

int i = 3;

for (;i++=0;) printf(―%d‖,i);

}

Answer:

Compiler Error: Lvalue required.

Explanation: As we know that increment operators return rvalues and hence it cannot appear

on the left hand side of an assignment operation.

Questions 133

void main()

{

int *mptr, *cptr;

mptr = (int*)malloc(sizeof(int));

printf(―%d‖,*mptr);

int *cptr = (int*)calloc(sizeof(int),1);

printf(―%d‖,*cptr);

}

Answer: garbage-value 0

Explanation: The memory space allocated by malloc is uninitialized, whereas calloc returns the

allocated memory space initialized to zeros.

Questions 134

void main()

{

static int i;

while(i<=10)

(i>2)?i++:i--;

printf(―%d‖, i);

}

© Copyright : IT Engg Portal – www.itportal.in 587

Answer: 32767

Explanation: Since i is static it is initialized to 0. Inside the while loop the conditional operator

evaluates to false, executing i--. Thiscontinues till the integer value rotates to

positive value (32767). The while condition becomes false and hence, comes out

of the while loop, printing the i value.

Questions 135

main()

{

int i=10,j=20;

j = i, j?(i,j)?i:j:j;

printf("%d %d",i,j);

}

Answer:

10 10

Explanation: The Ternary operator ( ? : ) is equivalent for if-then-else statement. So the

question can be written as:

if(i,j)

{

if(i,j)

j = i;

else

j = j;

}

else

j = j;

Questions 136

1. const char *a;

© Copyright : IT Engg Portal – www.itportal.in 588

2. char* const a;

3. char const *a;

-Differentiate the above declarations.

Answer:

1. 'const' applies to char * rather than 'a' ( pointer to a constant char )

*a='F' : illegal

a="Hi" : legal

2. 'const' applies to 'a' rather than to the value of a (constant pointer to char )

*a='F' : legal

a="Hi" : illegal

3. Same as 1.

Questions 137

main()

{

int i=5,j=10;

i=i&=j&&10;

printf("%d %d",i,j);

}

Answer:

1 10

Explanation: The expression can be written as i=(i&=(j&&10)); The inner expression (j&&10)

evaluates to 1 because j==10. i is 5. i = 5&1 is 1. Hence the result.

Questions 138

main()

© Copyright : IT Engg Portal – www.itportal.in 589

{

int i=4,j=7;

j = j || i++ && printf("YOU CAN");

printf("%d %d", i, j);

}

Answer:

4 1

Explanation: The boolean expression needs to be evaluated only till the truth value of the

expression is not known. j is not equal to zero itself means that the expression‘s

truth value is 1. Because it is followed by || and true || (anything) => true where

(anything) will not be evaluated. So the remaining expression is not evaluated and

so the value of i remains the same.

Similarly when && operator is involved in an expression, when any of the

operands become false, the whole expression‘s truth value becomes false and

hence the remaining expression will not be evaluated.

false && (anything) => false where (anything) will not be evaluated.

Questions 139

main()

{

register int a=2;

printf("Address of a = %d",&a);

printf("Value of a = %d",a);

}

Answer: Compier Error: '&' on register variable

Rule to Remember:

& (address of ) operator cannot be applied on register variables.

Questions 140

main()

© Copyright : IT Engg Portal – www.itportal.in 590

{

float i=1.5;

switch(i)

{

case 1: printf("1");

case 2: printf("2");

default : printf("0");

}

}

Answer: Compiler Error: switch expression not integral

Explanation: Switch statements can be applied only to integral types.

Questions 141

main()

{

extern i;

printf("%d\n",i);

{

int i=20;

printf("%d\n",i);

}

}

Answer: Linker Error : Unresolved external symbol i

Explanation: The identifier i is available in the inner block and so using extern has no use in

resolving it.

Questions 142

main()

{

int a=2,*f1,*f2;

© Copyright : IT Engg Portal – www.itportal.in 591

f1=f2=&a;

*f2+=*f2+=a+=2.5;

printf("\n%d %d %d",a,*f1,*f2);

}

Answer:

16 16 16

Explanation: f1 and f2 both refer to the same memory location a. So changes through f1 and f2

ultimately affects only the value of a.

Questions 143

main()

{

char *p="GOOD";

char a[ ]="GOOD";

printf("\n sizeof(p) = %d, sizeof(*p) = %d, strlen(p) = %d", sizeof(p), sizeof(*p),

strlen(p));

printf("\n sizeof(a) = %d, strlen(a) = %d", sizeof(a), strlen(a));

}

Answer:

sizeof(p) = 2, sizeof(*p) = 1, strlen(p) = 4

sizeof(a) = 5, strlen(a) = 4

Explanation: sizeof(p) => sizeof(char*) => 2

sizeof(*p) => sizeof(char) => 1

Similarly, sizeof(a) => size of the character array => 5

When sizeof operator is applied to an array it returns the sizeof the array and it is

not the same as the sizeof the pointervariable. Here the sizeof(a) where a is the

character array and the size of the array is 5 because the space necessary for the

terminating NULL character should also be taken into account.

© Copyright : IT Engg Portal – www.itportal.in 592

Questions 144

#define DIM( array, type) sizeof(array)/sizeof(type)

main()

{

int arr[10];

printf(―The dimension of the array is %d‖, DIM(arr, int));

}

Answer:

10

Explanation: The size of integer array of 10 elements is 10 * sizeof(int). The macro expands to

sizeof(arr)/sizeof(int) => 10 * sizeof(int) / sizeof(int) => 10.

Questions 145

int DIM(int array[])

{

return sizeof(array)/sizeof(int );

}

main()

{

int arr[10];

printf(―The dimension of the array is %d‖, DIM(arr));

}

Answer: 1

Explanation:

Arrays cannot be passed to functions as arguments and only the pointers can be

passed. So the argument is equivalent to int * array (this is one of the very few

places where [] and * usage are equivalent). The return statement becomes,

sizeof(int *)/ sizeof(int) that happens to be equal in this case.

Questions 146

main()

{

© Copyright : IT Engg Portal – www.itportal.in 593

static int a[3][3]={1,2,3,4,5,6,7,8,9};

int i,j;

static *p[]={a,a+1,a+2};

for(i=0;i<3;i++)

{

for(j=0;j<3;j++)

printf("%d\t%d\t%d\t%d\n",*(*(p+i)+j),

*(*(j+p)+i),*(*(i+p)+j),*(*(p+j)+i));

}

}

Answer:

1 1 1 1

2 4 2 4

3 7 3 7

4 2 4 2

5 5 5 5

6 8 6 8

7 3 7 3

8 6 8 6

9 9 9 9

Explanation:

*(*(p+i)+j) is equivalent to p[i][j].

Questions 147

main()

{

void swap();

© Copyright : IT Engg Portal – www.itportal.in 594

int x=10,y=8;

swap(&x,&y);

printf("x=%d y=%d",x,y);

}

void swap(int *a, int *b)

{

*a ^= *b, *b ^= *a, *a ^= *b;

}

Answer:

x=10 y=8

Explanation: Using ^ like this is a way to swap two variables without using a temporary

variable and that too in a single statement.

Inside main(), void swap(); means that swap is a function that may take

any number of arguments (not no arguments) and returns nothing. So this doesn‘t

issue a compiler error by the call swap(&x,&y); that has two arguments.

This convention is historically due to pre-ANSI style (referred to as Kernighan

and Ritchie style) style of function declaration. In that style, the swap function

will be defined as follows,

void swap()

int *a, int *b

{

*a ^= *b, *b ^= *a, *a ^= *b;

}

where the arguments follow the (). So naturally the declaration for swap will look

like, void swap() which means the swap can take any number of arguments.

© Copyright : IT Engg Portal – www.itportal.in 595

Questions 148

main()

{

int i = 257;

int *iPtr = &i;

printf("%d %d", *((char*)iPtr), *((char*)iPtr+1) );

}

Answer:

1 1

Explanation: The integer value 257 is stored in the memory as, 00000001 00000001, so the

individual bytes are taken by casting it to char * and get printed.

Questions 149

main()

{

int i = 258;

int *iPtr = &i;

printf("%d %d", *((char*)iPtr), *((char*)iPtr+1) );

}

Answer:

2 1

Explanation: The integer value 257 can be represented in binary as, 00000001 00000001.

Remember that the INTEL machines are ‗small-endian‘ machines. Small-endian

means that the lower order bytes are stored in the higher memory addresses and

the higher order bytes are stored in lower addresses. The integer value 258

is stored in memory as: 00000001 00000010.

Questions 150

main()

{

int i=300;

© Copyright : IT Engg Portal – www.itportal.in 596

char *ptr = &i;

*++ptr=2;

printf("%d",i);

}

Answer: 556

Explanation: The integer value 300 in binary notation is: 00000001 00101100. It is stored in

memory (small-endian) as: 00101100 00000001. Result of the expression *++ptr

= 2 makes the memory representation as: 00101100 00000010. So the integer

corresponding to it is 00000010 00101100 => 556.

Questions 151

#include <stdio.h>

main()

{

char * str = "hello";

char * ptr = str;

char least = 127;

while (*ptr++)

least = (*ptr<least ) ?*ptr :least;

printf("%d",least);

}

Answer: 0

Explanation: After ‗ptr‘ reaches the end of the string the value pointed by ‗str‘ is ‗\0‘. So the

value of ‗str‘ is less than that of ‗least‘. So the value of ‗least‘ finally is 0.

Questions 152

Declare an array of N pointers to functions returning pointers to functions

returning pointers to characters?

© Copyright : IT Engg Portal – www.itportal.in 597

Answer: (char*(*)( )) (*ptr[N])( );

Questions 153

main()

{

struct student

{

char name[30];

struct date dob;

}stud;

struct date

{

int day,month,year;

};

scanf("%s%d%d%d", stud.rollno, &student.dob.day,

&student.dob.month, &student.dob.year);

}

Answer: Compiler Error: Undefined structure date

Explanation: Inside the struct definition of ‗student‘ the member of type struct date is given.

The compiler doesn‘t have the definition ofdate structure (forward reference is

not allowed in C in this case) so it issues an error.

Questions 154

main()

{

struct date;

struct student

{

char name[30];

struct date dob;

}stud;

struct date

{

© Copyright : IT Engg Portal – www.itportal.in 598

int day,month,year;

};

scanf("%s%d%d%d", stud.rollno, &student.dob.day, &student.dob.month,

&student.dob.year);

}

Answer:

Compiler Error: Undefined structure date

Explanation: Only declaration of struct date is available inside the structure definition

of ‗student‘ but to have a variable of type struct date the definition

of the structure is required.

Questions 155

There were 10 records stored in ―somefile.dat‖ but the following program printed

11 names. What went wrong?

void main()

{

struct student

{

char name[30], rollno[6];

}stud;

FILE *fp = fopen(―somefile.dat‖,‖r‖);

while(!feof(fp))

{

fread(&stud, sizeof(stud), 1 , fp);

puts(stud.name);

}

}

Explanation: fread reads 10 records and prints the names successfully. It will return EOF only

when fread tries to read another record and fails reading EOF (and returning

EOF). So it prints the last record again. After this only the condition feof(fp)

becomes false, hence comes out of the while loop.

Questions 156

Is there any difference between the two declarations,

© Copyright : IT Engg Portal – www.itportal.in 599

1. int foo(int *arr[]) and

2. int foo(int *arr[2])

Answer:

No

Explanation: Functions can only pass pointers and not arrays. The numbers that are allowed

inside the [] is just for more readability. So there is no difference between the two

declarations.

Questions 157

What is the subtle error in the following code segment?

void fun(int n, int arr[])

{

int *p=0;

int i=0;

while(i++<n)

p = &arr[i];

*p = 0;

}

Answer & Explanation: If the body of the loop never executes p is assigned no address. So p remains

NULL where *p =0 may result in problem (may rise to runtime error ―NULL

pointer assignment‖ and terminate the program).

Questions 158

What is wrong with the following code?

int *foo()

{

int *s = malloc(sizeof(int)100);

assert(s != NULL);

return s;

}

© Copyright : IT Engg Portal – www.itportal.in 600

Answer & Explanation: assert macro should be used for debugging and finding out bugs. The check s !=

NULL is for error/exception handling and for that assert shouldn‘t be used. A

plain if and the corresponding remedy statement has to be given.

Questions 159

What is the hidden bug with the following statement?

assert(val++ != 0);

Answer & Explanation: Assert macro is used for debugging and removed in release version. In assert, the

experssion involves side-effects. So thebehavior of the code becomes different in

case of debug version and the release version thus leading to a subtle bug.

Rule to Remember:

Don‘t use expressions that have side-effects in assert statements.

Questions 160

void main()

{

int *i = 0x400; // i points to the address 400

*i = 0; // set the value of memory location pointed by i;

}

Answer:

Undefined behavior

Explanation: The second statement results in undefined behavior because it points to some

location whose value may not be available for modification. This type of pointer

in which the non-availability of the implementation of the referenced location is

known as 'incomplete type'.

Questions 161

#define assert(cond) if(!(cond)) \

© Copyright : IT Engg Portal – www.itportal.in 601

(fprintf(stderr, "assertion failed: %s, file %s, line %d \n",#cond,\

__FILE__,__LINE__), abort())

void main()

{

int i = 10;

if(i==0)

assert(i < 100);

else

printf("This statement becomes else for if in assert macro");

}

Answer:

No output

Explanation:

The else part in which the printf is there becomes the else for if in the

assert macro. Hence nothing is printed. The solution is to use conditional operator

instead of if statement,

#define assert(cond) ((cond)?(0): (fprintf (stderr, "assertion failed: \ %s, file %s,

line %d \n",#cond, __FILE__,__LINE__), abort()))

Note:

However this problem of ―matching with nearest else‖ cannot be solved by the

usual method of placing the if statement inside a block like this,

#define assert(cond) { \

if(!(cond)) \

(fprintf(stderr, "assertion failed: %s, file %s, line %d \n",#cond,\

__FILE__,__LINE__), abort()) \

}

Questions 162 Is the following code legal?

© Copyright : IT Engg Portal – www.itportal.in 602

struct a

{

int x;

struct a b;

}

Answer:

No

Explanation:

Is it not legal for a structure to contain a member that is of the same type as in this

case. Because this will cause the structure declaration to be

recursive without end.

Questions 163

Is the following code legal?

struct a

{

int x;

struct a *b;

}

Answer:

Yes.

Explanation:

*b is a pointer to type struct a and so is legal. The compiler knows, the size of the

pointer to a structure even before the sizeof the structure is determined(as you

know the pointer to any type is of same size). This type of structures is known as

‗self-referencing‘ structure.

Questions 164 Is the following code legal?

typedef struct a

{

int x;

aType *b;

}aType

© Copyright : IT Engg Portal – www.itportal.in 603

Answer:

No

Explanation:

The typename aType is not known at the point of declaring the structure

(forward references are not made for typedefs).

Questions 165

Is the following code legal?

typedef struct a aType;

struct a

{

int x;

aType *b;

};

Answer:

Yes

Explanation:

The typename aType is known at the point of declaring the structure, because it is

already typedefined.

Questions 166

Is the following code legal?

void main()

{

typedef struct a aType;

aType someVariable;

struct a

{

int x;

aType *b;

};

}

© Copyright : IT Engg Portal – www.itportal.in 604

Answer:

No

Explanation:

When the declaration, typedef struct a aType; is encountered body of

struct a is not known. This is known as ‗incomplete types‘.

Questions 167

void main()

{

printf(―sizeof (void *) = %d \n―, sizeof( void *));

printf(―sizeof (int *) = %d \n‖, sizeof(int *));

printf(―sizeof (double *) = %d \n‖, sizeof(double *));

printf(―sizeof(struct unknown *) = %d \n‖, sizeof(struct unknown *));

}

Answer : sizeof (void *) = 2

sizeof (int *) = 2

sizeof (double *) = 2

sizeof(struct unknown *) = 2

Explanation:

The pointer to any type is of same size.

Questions 168

char inputString[100] = {0};

To get string input from the keyboard which one of the following is better?

1) gets(inputString)

2) fgets(inputString, sizeof(inputString), fp)

Answer & Explanation:

The second one is better because gets(inputString) doesn't know the size of the

string passed and so, if a very big input (here, more than 100 chars) the charactes

will be written past the input string. When fgets is used with stdin performs the

same operation as gets but is safe.

Questions 169

Which version do you prefer of the following two,

© Copyright : IT Engg Portal – www.itportal.in 605

1) printf(―%s‖,str); // or the more curt one

2) printf(str);

Answer & Explanation:

Prefer the first one. If the str contains any format characters like %d then it

will result in a subtle bug.

Questions 170

void main()

{

int i=10, j=2;

int *ip= &i, *jp = &j;

int k = *ip/*jp;

printf(―%d‖,k);

}

Answer:

Compiler Error: ―Unexpected end of file in comment started in line 5‖.

Explanation:

The programmer intended to divide two integers, but by the ―maximum munch‖

rule, the compiler treats the operator sequence / and * as /* which happens to be

the starting of comment. To force what is intended by the programmer,

int k = *ip/ *jp;

// give space explicity separating / and *

//or

int k = *ip/(*jp);

// put braces to force the intention

will solve the problem.

Questions 171

void main()

© Copyright : IT Engg Portal – www.itportal.in 606

{

char ch;

for(ch=0;ch<=127;ch++)

printf(―%c %d \n―, ch, ch);

}

Answer:

Implementaion dependent

Explanation:

The char type may be signed or unsigned by default. If it is signed then ch++ is

executed after ch reaches 127 and rotates back to -128. Thus ch is always smaller

than 127.

Questions 172 Is this code legal?

int *ptr;

ptr = (int *) 0x400; Answer:

Yes

Explanation:

The pointer ptr will point at the integer in the memory location 0x400.

Questions 173

main()

{

char a[4]="HELLO";

printf("%s",a);

}

Answer:

Compiler error: Too many initializers

Explanation:

The array a is of size 4 but the string constant requires 6 bytes to get stored.

Questions 174

main()

{

char a[4]="HELL";

printf("%s",a);

© Copyright : IT Engg Portal – www.itportal.in 607

}

Answer:

HELL%@!~@!@???@~~!

Explanation:

The character array has the memory just enough to hold the string ―HELL‖ and

doesnt have enough space to store the terminating null character. So it prints the

HELL correctly and continues to print garbage values till it accidentally

comes across a NULL character.

Questions 175)

main()

{

int a=10,*j;

void *k;

j=k=&a;

j++;

k++;

printf("\n %u %u ",j,k);

}

Answer:

Compiler error: Cannot increment a void pointer

Explanation:

Void pointers are generic pointers and they can be used only when the type is not

known and as an intermediate address storage type. No pointer arithmetic can be

done on it and you cannot apply indirection operator (*) on void pointers.

Questions 176

main()

{

extern int i;

{ int i=20;

{

const volatile unsigned i=30; printf("%d",i);

}

© Copyright : IT Engg Portal – www.itportal.in 608

printf("%d",i);

}

printf("%d",i);

}

int i;

Questions177

Printf can be implemented by using __________ list.

Answer:

Variable length argument lists

Questions 178

char *someFun()

{

char *temp = ―string constant";

return temp;

}

int main()

{

puts(someFun());

}

Answer:

string constant

Explanation:

The program suffers no problem and gives the output correctly because

the character constants are stored in code/data area and not allocated in stack, so

this doesn‘t lead to dangling pointers.

Questions 179

char *someFun1()

{

char temp[ ] = ―string";

return temp;

}

char *someFun2()

{

© Copyright : IT Engg Portal – www.itportal.in 609

char temp[ ] = {‗s‘, ‗t‘,‘r‘,‘i‘,‘n‘,‘g‘};

return temp;

}

int main()

{

puts(someFun1());

puts(someFun2());

}

Answer:

Garbage values.

Explanation:

Both the functions suffer from the problem of dangling pointers. In someFun1()

temp is a character array and so the space forit is allocated in heap and is

initialized with character string ―string‖. This is created dynamically as the

function is called, so is also deleted dynamically on exiting the function so the

string data is not available in the calling function main() leading to print some

garbage values. The function someFun2() also suffers from the same problem but

the problem can be easily identified in this case.

© Copyright : IT Engg Portal – www.itportal.in 610

Bibliography

Material referenced from :

www.techpreparation.com

www.stackoverflow.com

www.indiabix.com

www.geekinterview.com

www.roseindia.com

© Copyright : IT Engg Portal – www.itportal.in 611

Regards :

Team – IT Engg Portal

(www.itportal.in)