Your SlideShare is downloading. ×
Complete placement guide(technical)
Upcoming SlideShare
Loading in...5
×

Thanks for flagging this SlideShare!

Oops! An error has occurred.

×
Saving this for later? Get the SlideShare app to save on your phone or tablet. Read anywhere, anytime – even offline.
Text the download link to your phone
Standard text messaging rates apply

Complete placement guide(technical)

12,845
views

Published on

must read...

must read...

Published in: Career

0 Comments
3 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total Views
12,845
On Slideshare
0
From Embeds
0
Number of Embeds
0
Actions
Shares
0
Downloads
272
Comments
0
Likes
3
Embeds 0
No embeds

Report content
Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
No notes for slide

Transcript

  • 1. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.IN The Complete Placement Guide for IT Companies (Technical) © IT Engineering Portal : www.itportal.in 1
  • 2. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.IN ContentsTopics Page • Preface 03 • Technical Data Structure Interview Questions 04 C++ Interview Questions 14 Java Interview Questions 49 JDBC Interview Questions 124 Oracle Interview Questions 191 Networking Interview Questions 326 Operating Systems Interview Questions 344 C Aptitude Questions 350 © IT Engineering Portal : www.itportal.in 2
  • 3. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.INPreface Placements are always a headache for most of the Engineeringstudents. Usually, a majority of the students are always in a state ofconfusion for deciding which book to refer, where to start from andwhich company to target. When a student gets to know about the arrivalof a company in the campus, he would then start preparing for the test.Namely, a student will start preparing for the technical interview,aptitude test, Group Discussion, HR Interview and all other necessarytests. Now the biggest problem is the availability of resources in studymaterial for preparing for these tests. We have thus identified the major areas where a student shouldprepare himself for an aptitude test or a technical interview so as to getplaced into an IT company. The technical fields are viz: C, C++, Java,Oracle, JDBC, Operating Systems and Networking. Similarly, amongst thenon-technical fields a student needs to mentally prepare himself for anaptitude test and a HR interview. All the basic study material required toprepare concerning the above related fields are deployed in this book The book makes available all available resources over the internet tothe students in a simple and compiled format. Regards Team : IT Engg Portal © IT Engineering Portal : www.itportal.in 3
  • 4. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.IN Data Structures Interview Questions & Answers © IT Engineering Portal : www.itportal.in 4
  • 5. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.INData Structures Interview Questions and AnswersWhat is data structure?A data structure is a way of organizing data that considers not only the items stored, butalso their relationship to each other. Advance knowledge about the relationship betweendata 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 analysispackage, Numerical Analysis, Graphics, Artificial Intelligence, SimulationIf you are using C language to implement the heterogeneous linked list, whatpointer type will you use?The heterogeneous linked list contains different data types in its nodes and we need alink, pointer to connect them. It is not possible to use ordinary pointers for this. So we gofor void pointer. Void pointer is capable of storing pointer to any type as it is a genericpointer 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 knowswhom to return when the function has to return. Recursion makes use of system stackfor storing the return addresses of the function calls. Every recursive function has itsequivalent iterative (non-recursive) function. Even when such equivalent iterativeprocedures 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 storagerepresentation?B+ tree. Because in B+ tree, all the data is stored only in leaf nodes, that makessearching easier. This corresponds to the records that shall be stored in leaf nodes.What is a spanning Tree?A spanning tree is a tree associated with a network. All the nodes of the graph appear onthe tree once. A minimum spanning tree is a spanning tree organized so that the totaledge weight between nodes is minimized.Does the minimum spanning tree of a graph give the shortest distance betweenany 2 specified nodes?Minimal spanning tree assures that the total weight of the tree is kept at its minimum.But it doesnt mean that the distance between any two nodes involved in the minimum-spanning tree is minimum. © IT Engineering Portal : www.itportal.in 5
  • 6. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.INWhether Linked List is linear or Non-linear data structure?According to Access strategies Linked list is a linear one. According to Storage LinkedList 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 justdoesnt matter how quick the sort is because it is done infrequently or other operationstake significantly more time anyway. Even in cases in which sorting speed is of theessence, 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 sortingmethods in this authors toolbox that are all very fast and that are useful in differentsituations. Those methods are quick sort, merge sort, and radix sort.The Quick SortThe quick sort algorithm is of the divide and conquer type. That means it works byreducing 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 threesets: elements that belong before the dividing value, the value itself, and elements thatcome after the dividing value. The partitioning is performed by exchanging elements thatare in the first set but belong in the third with elements that are in the third set butbelong in the first Elements that are equal to the dividing element can be put in any ofthe three sets the algorithm will still work properly.The Merge SortThe merge sort is a divide and conquer sort as well. It works by considering the data tobe sorted as a sequence of already-sorted lists (in the worst case, each list is one elementlong). Adjacent sorted lists are merged into larger sorted lists until there is a single sortedlist containing all the elements. The merge sort is good at sorting lists and other datastructures that are not in arrays, and it can be used to sort things that dont fit intomemory. It also can be implemented as a stable sort.The Radix SortThe radix sort takes a list of integers and puts each element on a smaller list, dependingon the value of its least significant byte. Then the small lists are concatenated, and theprocess is repeated for each more significant byte until the list is sorted. The radix sort issimpler 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 theonly way a linked lists members can be accessed is sequentially. Sometimes it is quickerto take the data from a linked list and store it in a different data structure so thatsearches 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 © IT Engineering Portal : www.itportal.in 6
  • 7. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.INother hand, the heap is much more flexible than the stack. Memory can be allocated atany time and deallocated in any order. Such memory isnt deallocated automatically; youhave 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. Ifyou can keep data in a local variable (and allocate it from the stack), your code will runfaster than if you put the data on the heap. Sometimes you can use a better algorithm ifyou 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. Thats great ifyou remember to deallocate it when youre done. If you forget, its a problem. A �memoryleak is some allocated memory thats no longer needed but isnt deallocated. If you have amemory leak inside a loop, you can use up all the memory on the heap and not be ableto get any more. (When that happens, the allocation functions return a null pointer.) Insome environments, if a program doesnt deallocate everything it allocated, memory staysunavailable even after the program ends.What is the easiest sorting method to use?The answer is the standard library function qsort(). Its the easiest sort by far for severalreasons: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 isno 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 maximumcombination 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 virtualfunctions in its public interface depends on all its direct and indirect base class can beunderstood only in the context of the base class can be used as base for furtherderivationcan be used to create objects. A node class is a class that has added new services orfunctionality beyond the services inherited from its base class. © IT Engineering Portal : www.itportal.in 7
  • 8. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.INWhen can you tell that a memory leak will occur?A memory leak occurs when a program loses the ability to free a block of dynamicallyallocated memory.What is placement new?When you want to call a constructor directly, you use the placement new. Sometimes youhave some raw memory that’s already been allocated, and you need to construct anobject in the memory you have. Operator new’s special version placement new allows youto 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 bufferpassed to the function. Such a function might be useful for applications using sharedmemory or memory-mapped I/O, because objects in such applications must be placed atspecific 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 analysispackage, Numerical Analysis, Graphics, Artificial Intelligence, SimulationIf you are using C language to implement the heterogeneous linked list, whatpointer type will you use?The heterogeneous linked list contains different data types in its nodes and we need alink, pointer to connect them. It is not possible to use ordinary pointers for this. So we gofor void pointer. Void pointer is capable of storing pointer to any type as it is a genericpointer 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 knowswhom to return when the function has to return. Recursion makes use of system stackfor storing the return addresses of the function calls. Every recursive function has itsequivalent iterative (non-recursive) function. Even when such equivalent iterativeprocedures are written, explicit stack is to be used.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 © IT Engineering Portal : www.itportal.in 8
  • 9. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.INTell 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 (”circularn”);}}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 accessis 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 ofdigits 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 getone 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 numberplus 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 languageimplementation 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 forthe data that it will point to. The memory for the data pointed by a pointer has to beallocated at runtime.The memory reserved by the compiler for simple variables and for storing pointer address © IT Engineering Portal : www.itportal.in 9
  • 10. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.INis allocated on the stack, while the memory allocated for pointer referenced data atruntime 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 optionalwhich 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 anattribute 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 isusually the memory address of another variable, element of a structure, or attribute of aclass.What is Data Structure?A data structure is a group of data elements grouped together under one name. Thesedata elements, known as members, can have different types and different lengths. Someare used to store the data of same type and some are used to store different types ofdata.What is significance of ” * ” ?The symbol “*” tells the computer that you are declaring a pointer.Actually it depends on context.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 tovariable 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. Inaddition to organizing data stored in elements of an array, a multidimensional array canstore 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 floorof 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 addressoperator, 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 © IT Engineering Portal : www.itportal.in 10
  • 11. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.INdynamically allocate memory by using the new operator when declaring the array, forexample : 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 thenreturned by the pop() member method to the statement that calls the pop() membermethod.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.What is a queue ?A Queue is a sequential organization of data. A queue is a first in first out type of datastructure. An element is inserted at the last position and an element is always taken outfrom 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 beused 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 thelast index available it will be reset to 0. Then it will be checked with end. If it is greaterthan end queue is empty.When an element is added end will be incremented by 1. In case it reaches past the lastindex available it will be reset to 0. After incrementing it will be checked with front. Ifthey 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 thereis an item in the queue to be removed i.e. isEmpty() is called to decide whether the queuehas at least one element. This method is called by the dequeue() method before returningthe 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 © IT Engineering Portal : www.itportal.in 11
  • 12. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.INsub entries. One sub entry contains the data, which may be one attribute or manyattributes. 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 thepointers to previous and next nodes.What is Linked List ?Linked List is one of the fundamental data structures. It consists of a sequence of?nodes, each containing arbitrary data fields and one or two (”links”) pointing to the nextand/or previous nodes. A linked list is a self-referential datatype because it contains apointer or link to another data of the same type. Linked lists permit insertion andremoval of nodes at any point in the list in constant time, but do not allow randomaccess.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. TheappendNode() 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 mainapplication file. The first file is the header file that contains the definition of the NODEstructure and the LinkedList class definition. The second file is a source code filecontaining the implementation of member functions of the LinkedList class. The last fileis 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 theLinkedList.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 Graph3. Hierarchical data model Trees.Difference between calloc and malloc ?malloc: allocate n bytescalloc: allocate m times n bytes initialized to 0 © IT Engineering Portal : www.itportal.in 12
  • 13. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.IN C++ Interview Questions & Answers © IT Engineering Portal : www.itportal.in 13
  • 14. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.IN C++ Interview Questions and AnswersWhat is C++?Released in 1985, C++ is an object-oriented programming language created by BjarneStroustrup. C++ maintains almost all aspects of the C language, while simplifyingmemory management and adding several features - including a new datatype known as aclass (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 theprogrammer new tools to simplify memory management.C++ used for:C++ is a powerful general-purpose programming language. It can be used to create smallprograms or large applications. It can be used to make CGI scripts or console-only DOSprograms. C++ allows you to create programs to do almost anything you need to do. Thecreator of C++, Bjarne Stroustrup, has put together a partial list of applications writtenin 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 secondone goes at 1 nodes each time. If there is a cycle, the one that goes 2 nodes each time willeventually meet the one that goes slower. If that is the case, then you will know thelinked-list is a cycle.What is the difference between realloc() and free()?The free subroutine frees a block of memory previously allocated by the mallocsubroutine. Undefined results occur if the Pointer parameter is not a valid pointer. If thePointer parameter is a null value, no action will occur. The realloc subroutine changesthe size of the block of memory pointed to by the Pointer parameter to the number ofbytes specified by the Size parameter and returns a new pointer to the block. The pointerspecified by the Pointer parameter must have been created with the malloc, calloc, orrealloc 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, aslong as these functions have different sets of parameters (at least as far as their types areconcerned). This capability is called function overloading. When an overloaded functionis called, the C++ compiler selects the proper function by examining the number, typesand order of the arguments in the call. Function overloading is commonly used to createseveral functions of the same name that perform similar tasks but on different datatypes.Operator overloading allows existing C++ operators to be redefined so that they work on © IT Engineering Portal : www.itportal.in 14
  • 15. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.INobjects of user-defined classes. Overloaded operators are syntactic sugar for equivalentfunction calls. They form a pleasant facade that doesnt add anything fundamental to thelanguage (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 thedefinition of this declaration.E.g.: void stars () //function declarationThe definition contains the actual implementation.E.g.: void stars () // declarator{for(int j=10; j > =0; j--) //function bodycout << *;cout << endl; }What are the advantages of inheritance?It permits code reusability. Reusability saves time in program development. It encouragesthe reuse of proven and debugged high-quality software, thus reducing problem after asystem 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; © IT Engineering Portal : www.itportal.in 15
  • 16. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.INpre = cur;cur = curnext;curnext = curnext->next;}curnext->next = cur;}}What do you mean by inline function?The idea behind inline functions is to insert the code of a called function at the pointwhere the function is called. If done carefully, this can improve the applicationsperformance in exchange for increased compile time and possibly (but not always) anincrease 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 afor loopfor( 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.Protected data members and member functions are only available to derived classes. © IT Engineering Portal : www.itportal.in 16
  • 17. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.INPrivate 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 ("circularn");}}OK, why does this work?If a list is circular, at some point pointer2 will wrap around and be either at the item justbefore pointer1, or the item before that. Either way, it’s either 1 or 2 jumps until theymeet.What is virtual constructors/destructors?Answer1Virtual destructors:If an object (with a non-virtual destructor) is destroyed explicitly by applying the deleteoperator 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 samename as the base-class destructor. Now, if the object in the hierarchy is destroyedexplicitly 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: Constructorscannot be virtual. Declaring a constructor as a virtual function is a syntax error.Answer2Virtual destructors: If an object (with a non-virtual destructor) is destroyed explicitly byapplying the delete operator to a base-class pointer to the object, the base-classdestructor function (matching the pointer type) is called on the object.There is a simple solution to this problem – declare a virtual base-class destructor. Thismakes all derived-class destructors virtual even though they don’t have the same nameas the base-class destructor. Now, if the object in the hierarchy is destroyed explicitly by © IT Engineering Portal : www.itportal.in 17
  • 18. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.INapplying the delete operator to a base-class pointer to a derived-class object, thedestructor for the appropriate class is called.Virtual constructor: Constructors cannot be virtual. Declaring a constructor as avirtual function is a syntax error. Does c++ support multilevel and multipleinheritance?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 reducingproblem 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 thedefinition of this declaration.E.g.: void stars () //function declarationThe definition contains the actual implementation.E.g.: void stars () // declarator{for(int j=10; j>=0; j--) //function bodycout<<”*”;cout<<endl; }What is the difference between an ARRAY and a LIST?Answer1Array 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.Answer2Array uses direct access of stored members, list uses sequencial access for members.//With Array you have direct access to memory position 5Object 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++ ) © IT Engineering Portal : www.itportal.in 18
  • 19. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.IN{if( i==5){x = *it;break;}i++;}Does c++ support multilevel and multiple inheritance?Yes.What is a template?Templates allow to create generic functions that admit any data type as parameters andreturn 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 twofollowing 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, itsuse is indistinct since both expressions have exactly the same meaning and behaveexactly the same way.Define a constructor - What it is and how it might be called (2 methods).Answer1constructor is a member function of the class, with the name of the function being thesame 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.Answer2class 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, thedefault constructor is implicitly called. © IT Engineering Portal : www.itportal.in 19
  • 20. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.INPoint2D * pPoint = new Point2D(); // Explicit Constructor call. In order to allocatememory on HEAP we call the default constructor.You have two pairs: new() and delete() and another pair : alloc() and free().Explain differences between eg. new() and malloc()Answer11.) “new and delete” are preprocessors while “malloc() and free()” are functions. [we dontuse 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 newalloted memory location [better to use calloc()]Answer2new() allocates continous space for the object instacemalloc() 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 typestogether to perform a particular functionality. But C++ extended the structure to containfunctions also. The major difference is that all declarations inside a structure are bydefault public.Class: Class is a successor of Structure. By default all the members inside the class areprivate.What is RTTI?Runtime type identification (RTTI) lets you find the dynamic type of an object when youhave only a pointer or a reference to the base type. RTTI is the official way in standardC++ 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++. RTTIreplaces many Interview Questions - Homegrown versions with a solid, consistentapproach.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 Ihave a base class SHAPE, how would I define DRAW methods for two objectsCIRCLE and SQUAREAnswer1POLYMORPHISM : A phenomenon which enables an object to react differently to thesame function call.in C++ it is attained by using a keyword virtual © IT Engineering Portal : www.itportal.in 20
  • 21. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.INExamplepublic class SHAPE{public virtual void SHAPE::DRAW()=0;}Note here the function DRAW() is pure virtual which means the sub classes mustimplement the DRAW() method and SHAPE cannot be instatiatedpublic 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 likegloballySHAPE *newShape;When user action is to drawpublic void MENU::OnClickDrawCircle(){newShape = new CIRCLE();}public void MENU::OnClickDrawCircle(){newShape = new SQUARE();}the when user actually drawspublic void CANVAS::OnMouseOperations(){newShape->DRAW();}Answer2class SHAPE{public virtual Draw() = 0; //abstract class with a pure virtual method © IT Engineering Portal : www.itportal.in 21
  • 22. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.IN};class CIRCLE{public int r;public virtual Draw() { this->drawCircle(0,0,r); }};class SQUREpublic 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.What is an object?Object is a software bundle of variables and related methods. Objects have state andbehavior.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 randomnumbers if you are from the Korn shell. You could also do a ps -l and look for the shellwith the highest PID.What do you mean by inheritance?Inheritance is the process of creating new classes, called derived classes, from existingclasses 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 © IT Engineering Portal : www.itportal.in 22
  • 23. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.INOn the other hand, you can assign and read the public data members:MyPoint.color = 255; // no problemint col = MyPoint.color; // no problemWith protected data members you can read them but not write them: MyPoint.pinned =true; // Compiler will issue a compile ERRORbool isPinned = MyPoint.pinned; // no problemWhat is namespace?Namespaces allow us to group a set of global classes, objects and/or functions under aname. To say it somehow, they serve to split the global scope in sub-scopes known asnamespaces.The form to use namespaces is:namespace identifier { namespace-body }Where identifier is any valid identifier and namespace-body is the set of classes, objectsand functions that are included within the namespace. For example:namespace general { int a, b; } In this case, a and b are normal variables integratedwithin the general namespace. In order to access to these variables from outside thenamespace we have to use the scope operator ::. For example, to access the previousvariables we would have to put:general::a general::bThe functionality of namespaces is specially useful in case that there is a possibility thata global object or function can have the same name than another one, causing aredefinition 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’sdata 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) constructorpublic Point2D( const Point2D & ) ;};Point2D::Point2D( const Point2D & p ){this->x = p.x;this->y = p.y;this->color = p.color;this->pinned = p.pinned;} © IT Engineering Portal : www.itportal.in 23
  • 24. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.INmain(){Point2D MyPoint;MyPoint.color = 345;Point2D AnotherPoint = Point2D( MyPoint ); // now AnotherPoint has color = 345What is Boyce Codd Normal form?A relation schema R is in BCNF with respect to a set F of functional dependencies if forall functional dependencies in F+ of the form a-> , where a and b is a subset of R, at leastone of the following holds:* a- > b is a trivial functional dependency (b is a subset of a)* a is a superkey for schema RWhat is virtual class and friend class?Friend classes are used when two or more classes are designed to work together andneed access to each others implementation in ways that the rest of the world shouldntbe allowed to have. In other words, they help keep private things private. For instance, itmay be desirable for class DatabaseCursor to have more privilege to the internals of classDatabase than main() has.What is the word you will use when defining a function in base class to allow thisfunction to be a polimorphic function?virtualWhat 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 LibraryWhat is the difference between an object and a class?Classes and objects are separate but related concepts. Every object belongs to a classand 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 theexecution of a program. The attributes of a class dont change.- The class to which an object belongs is also (usually) static. If a particular objectbelongs to a certain class at the time that it is created then it almost certainly will stillbelong 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 eventuallydestroyed. Also during that lifetime, the attributes of the object may undergo significantchange.Suppose that data is an array of 1000 integers. Write a single function call thatwill sort the 100 elements data [222] through data [321].quicksort ((data + 222), 100); © IT Engineering Portal : www.itportal.in 24
  • 25. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.INWhat is a class?Class is a user-defined data type in C++. It can be created to solve a particular kind ofproblem. 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, itcan access its private and protected members. A friend function is not a member of theclass. But it must be listed in the class definition.Which recursive sorting technique always makes recursive calls to sortsubarrays that are about half size of the original array?Mergesort always makes recursive calls to sort subarrays that are about half size of theoriginal 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 thebase class. The compiler makes sure the replacement is always called whenever theobject in question is actually of the derived class, even if the object is accessed by a basepointer rather than a derived pointer. This allows algorithms in the base class to bereplaced in the derived class, even if users dont 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 tostep 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 theadvantage that many difference iterators can be active simultaneously on the sameobject.What is a scope resolution operator?A scope resolution operator (::), can be used to define the member functions of a classoutside the class.What do you mean by pure virtual functions?A pure virtual member function is a member function that the base class forces derivedclasses to provide. Normally these member functions have no implementation. Purevirtual 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 © IT Engineering Portal : www.itportal.in 25
  • 26. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.INcan be a plus ‘+’ sign, used for adding two integers or for using it to concatenate twostrings.What’s the output of the following program? Why?#include <stdio.h>main(){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 inoutput = (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 traversethe array, accessing each element with the same expression a[i]. All the is needed tomake 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 abbreviatesspecific 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 inFORTRAN.Explain which of the following declarations will compile and what will beconstant - a pointer or the value pointed at: * const char ** char const ** char * constNote: Ask the candidate whether the first declaration is pointing to a string or a single © IT Engineering Portal : www.itportal.in 26
  • 27. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.INcharacter. Both explanations are correct, but if he says that it’s a single characterpointer, ask why a whole string is initialized as char* in C++. If he says this is a stringdeclaration, ask him to declare a pointer to a single character. Competent candidatesshould not have problems pointing out why const char* can be both a character and astring declaration, incompetent ones will come up with invalid reasons.You’re given a simple code for the class Bank Customer. Write the followingfunctions:* Copy constructor* = operator overload* == operator overload* + operator overload (customers’ balances should be added up, as an example of jointaccount between husband and wife)Note:Anyone confusing assignment and equality operators should be dismissed from theinterview. The applicant might make a mistake of passing by value, not by reference. Thecandidate might also want to return a pointer, not a new object, from the additionoperator. 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 + customer2would work in the second case.What problems might the following macro bring to the application?#define sq(x) x*xAnything wrong with this code?T *p = new T[10];delete p;Everything is correct, Only the first element of the array will be deleted”, The entire arraywill 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 weuse long int.A char is for 1-byte integers, a short is for 2-byte integers, an int is generally a 2-byte or4-byte integer (though not necessarily), a long is a 4-byte integer, and a long long is a 8-byte integer. © IT Engineering Portal : www.itportal.in 27
  • 28. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.INWhat does extern mean in a function declaration?Using extern in a function declaration we can make a function such that it can usedoutside the file in which it is defined.An extern variable, function definition, or declaration also makes the described variableor function usable by the succeeding part of the current source file. This declaration doesnot replace the definition. The declaration is used to describe the variable that isexternally defined.If a declaration for an identifier already exists at file scope, any extern declaration of thesame identifier found within a block refers to that same object. If no other declaration forthe identifier exists at file scope, the identifier has external linkage.What can I safely assume about the initial values of variables which are notexplicitly initialized?It depends on complier which may assign any garbage value to a variable if it is notinitialized.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 thesecond case if *p is assigned to some other value the allocate memory can change.What’s the auto keyword good for?Answer1Not much. It declares an object with automatic storage duration. Which means the objectwill be destroyed at the end of the objects scope. All variables in functions that are notdeclared as static and not dynamically allocated have automatic storage duration bydefault.For exampleint main(){int a; //this is the same as writing “auto int a;”}Answer2Local variables occur within a scope; they are “local” to a function. They are often calledautomatic variables because they automatically come into being when the scope isentered and automatically go away when the scope closes. The keyword auto makes thisexplicit, but local variables default to auto auto auto auto so it is never necessary todeclare something as an auto auto auto auto.What is the difference between char a[] = “string”; and char *p = “string”; ?Answer1a[] = “string”;char *p = “string”; © IT Engineering Portal : www.itportal.in 28
  • 29. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.INThe difference is this:p is pointing to a constant string, you can never safely sayp[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 caseof char pointer in C++ to preserve backward compatibility with C.)Answer2a[] = “string”;char *p = “string”;a[] will have 7 bytes. However, p is only 4 bytes. P is pointing to an adress is either BSSor the data section (depending on which compiler — GNU for the former and CC for thelatter).Answer3char a[] = “string”;char *p = “string”;for char a[]…….using the array notation 7 bytes of storage in the static memory block aretaken 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 tostore the pointer variable “p” (where N depends on the system but is usually a minimumof 2 bytes and can be 4 or more)……How do I declare an array of N pointers to functions returning pointers to functionsreturning pointers to characters?Answer1If 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 integralAnswer2char* (* (*a[N])())()Here a is that array. And according to question no function will not take any parametervalue.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 yetseen it in the file currently being compiled. This variable or function may be defined inanother file or further down in the current file. © IT Engineering Portal : www.itportal.in 29
  • 30. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.INHow do I initialize a pointer to a function?This is the way to initialize a pointer to a functionvoid 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 hiddenby 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. Thefirst format uses the traditional C notation. The second format uses constructornotation.int foo = 123;int bar (123);How does throwing and catching exceptions differ from using setjmp andlongjmp?The throw operation calls the destructors for automatic objects instantiated since entryto the try block.What is a default constructor?Default constructor WITH arguments class B { public: B (int m = 0) : n (m) {} int n; }; intmain(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 overloadedassignment operator? © IT Engineering Portal : www.itportal.in 30
  • 31. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.INA 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 anotherexisting object of the same class.When should you use multiple inheritance?There are three acceptable answers: "Never," "Rarely," and "When the problem domaincannot be accurately modeled any other way."Explain the ISA and HASA class relationships. How would you implement each ina class design?A specialized class "is" a specialization of another class and, therefore, has the ISArelationship with the other class. An Employee ISA Person. This relationship is bestimplemented with inheritance. Employee is derived from Person. A class may have aninstance of another class. For example, an employee "has" a salary, therefore theEmployee class has the HASA relationship with the Salary class. This relationship is bestimplemented 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 othertypes, when the format and behavior of those other types are unimportant to theircontainment 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 memberfunction doing the modification is const.What is an explicit constructor?A conversion constructor declared with the explicit keyword. The compiler does not usean explicit constructor to implement an implied conversion of types. It’s purpose isreserved explicitly for construction.What is the Standard Template Library (STL)?A library of container templates approved by the ANSI committee for inclusion in thestandard 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 ofthe 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 orthe dynamic_cast operator.What problem does the namespace feature solve?Multiple providers of libraries might use common global identifiers causing a namecollision when an application tries to link with two or more such libraries. Thenamespace feature surrounds a library’s external declarations with a unique namespace © IT Engineering Portal : www.itportal.in 31
  • 32. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.INthat 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 valuekeywords.Will the following program execute?void main(){void *vptr = (void *) malloc(sizeof(void));vptr++;}Answer1It will throw an error, as arithmetic operations cannot be performed on void pointers.Answer2It will not build as sizeof cannot be applied to void* ( error “Unknown size” )Answer3How can it execute if it won’t even compile? It needs to be int main, not void main. Also,cannot increment a void *.Answer4According to gcc compiler it won’t show any error, simply it executes. but in general wecan’t do arthematic operation on void, and gives size of void as 1Answer5The program compiles in GNU C while giving a warning for “void main”. The programruns without a crash. sizeof(void) is “1? hence when vptr++, the address is incrementedby 1.Answer6Regarding arguments about GCC, be aware that this is a C++ question, not C. So gcc willcompile and execute, g++ cannot. g++ complains that the return type cannot be void andthe argument of sizeof() cannot be void. It also reports that ISO C++ forbids incrementinga pointer of type ‘void*’.Answer7in C++voidp.c: In function `int main()’:voidp.c:4: error: invalid application of `sizeof’ to a void typevoidp.c:4: error: `malloc’ undeclared (first use this function)voidp.c:4: error: (Each undeclared identifier is reported only once for each function itappears in.) © IT Engineering Portal : www.itportal.in 32
  • 33. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.INvoidp.c:6: error: ISO C++ forbids incrementing a pointer of type `void*’But in c, it work without problemsvoid main(){char *cptr = 0?2000;long *lptr = 0?2000;cptr++;lptr++;printf(” %x %x”, cptr, lptr);}Will it execute or not?Answer1For Q2: As above, won’t compile because main must return int. Also, 0×2000 cannot beimplicitly converted to a pointer (I assume you meant 0×2000 and not 0?2000.)Answer2Not 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 2004Answer3In C++[$]> g++ point.cpoint.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.cpoint.c: In function `main’:point.c:4: warning: initialization makes pointer from integer without a castpoint.c:5: warning: initialization makes pointer from integer without a cast[$] etc > ./a.exe2001 2004 © IT Engineering Portal : www.itportal.in 33
  • 34. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.INWhat is the difference between Mutex and Binary semaphore?semaphore is used to synchronize processes. where as mutex is used to providesynchronization between threads running in the same process.In C++, what is the difference between method overloading and methodoverriding?Overloading a method (or function) in C++ is the ability for functions of the same name tobe defined as long as these methods have different signatures (different set ofparameters). Method overriding is the ability of the inherited class rewriting the virtualmethod of the base class.What methods can be overridden in Java?In C++ terminology, all public methods in Java are virtual. Therefore, all Java methodscan 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* polymorphismWrite a program that ask for user input from 5 to 9 then calculate the averageint 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";elsefor(i=0;i<=MAX; i++){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. © IT Engineering Portal : www.itportal.in 34
  • 35. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.INIn assignment operator, you are assigning a value to an existing object. But in copyconstructor, you are creating a new object and then assigning a value to that object. Forexample:complex c1,c2;c1=c2; //this is assignmentcomplex c3=c2; //copy constructorAnswer2.A copy constructor is used to initialize a newly declared variable from an existingvariable. 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 findout the exact type of the objet of which it is member. It can be done by using:1) dynamic id operator2) typecast operatorAnswer2.RTTI is defined as follows: Run Time Type Information, a facility that allows an object tobe queried at runtime to determine its type. One of the fundamental principles of objecttechnology is polymorphism, which is the ability of an object to dynamically change atruntime.STL Containers - What are the types of STL containers?There are 3 types of STL containers:1. Adaptive containers like queue, stack2. Associative containers like set, map3. Sequence containers like vector, dequeWhat is the need for a Virtual Destructor ?Destructors are declared as virtual because if do not declare it as virtual the base classdestructor will be called before the derived class destructor and that will lead to memoryleak because derived class’s objects will not get freed.Destructors are declared virtualso 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 canchange. When we want one of its members to change, we declare it as mutable. © IT Engineering Portal : www.itportal.in 35
  • 36. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.INAnswer2.A "mutable" keyword is useful when we want to force a "logical const" data memberto have its value modified. A logical const can happen when we declare a datamember as non-const, but we have a const member function attempting to modifythat data member. For example:class Dummy {public:bool isValid() const;private:mutable int size_ = 0;mutable bool validStatus_ = FALSE;// logical const issue resolved};bool Dummy::isValid() const// data members become bitwise const{if (size > 10) {validStatus_ = TRUE; // fine to assignsize = 0; // fine to assign}}Answer2."mutable" keyword in C++ is used to specify that the member may be updated ormodified 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 © IT Engineering Portal : www.itportal.in 36
  • 37. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.INextern const int i;C compiler will not complain.But for C++ compiler u must writeextern const int i = 2;else error would be generated.Bitwise Operations - Given inputs X, Y, Z and operations | and & (meaningbitwise OR and AND, respectively), what is output equal to in?output = (X & Y) | (X & Z) | (Y & Z);C++ Object-Oriented Interview Questions And AnswersWhat is a modifier?A modifier, also called a modifying function is a member function that changes thevalue of at least one data member. In other words, an operation that modifies thestate of an object. Modifiers are also known as ‘mutators’. Example: The functionmod 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;}};What is an accessor?An accessor is a class operation that does not modify the state of an object. Theaccessor functions need to be declared as const operationsDifferentiate between a template class and class template.Template class: A generic definition or a parameterized class not instantiated until theclient provides the needed information. It’s jargon for plain templates. Class template: Aclass template specifies how individual classes can be constructed much like the way aclass specifies how individual objects can be constructed. It’s jargon for plain classes. © IT Engineering Portal : www.itportal.in 37
  • 38. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.INWhen does a name clash occur?A name clash occurs when a name is defined in more than one place. For example., twodifferent class libraries could give two different classes the same name. If you try to usemany class libraries at the same time, there is a fair chance that you will be unable tocompile 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. Thisnamespace keyword assigns a distinct name to a library that allows other libraries to usethe same identifier names without creating any name collisions. Furthermore, thecompiler 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 scopeoperator.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 thecontents of a container object without violating encapsulation constraints. Access to thecontents is granted on a one-at-a-time basis in order. The order can be storage order (asin lists and queues) or some arbitrary order (as in array indices) or according to someordering relation (as in an ordered binary tree). The iterator is a construct, whichprovides an interface that, when called, yields either the next element in the container, orsome value denoting the fact that there are no more elements to examine. Iterators hidethe details of access to and update of the elements of a container class.The simplest and safest iterators are those that permit read-only access to the contentsof a container class.What is an incomplete type?Incomplete types refers to pointers in which there is non availability of theimplementation of the referenced location or it points to some location whose value is notavailable 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 afterits lifetime is over. This may occur in situations like returningaddresses of the automatic variables from a function or using theaddress of the memory block after it is freed. The followingcode snippet shows this: © IT Engineering Portal : www.itportal.in 38
  • 39. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.INclass Sample{public:int *ptr;Sample(int i){ptr = new int(i);}~Sample(){delete ptr;}void PrintVal(){cout << "The value is " << *ptr;}};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 iscalled it is called by the pointer that has been freed by thedestructor 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 © IT Engineering Portal : www.itportal.in 39
  • 40. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.INparty 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 classdoes not exist. One common use for a null object is a return value from a memberfunction that is supposed to return an object with some specified properties but cannotfind such an object.What is class invariant?A class invariant is a condition that defines all valid states for an object. It is a logicalcondition to ensure the correct working of a class. Class invariants must hold when anobject is created, and they must be preserved under all operations of the class. Inparticular all class invariants are both preconditions and post-conditions for alloperations 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 localobjects 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 memberfunction. A class is used correctly if preconditions are never false. An operation is notresponsible for doing anything sensible if its precondition fails to hold. For example, theinterface invariants of stack class say nothing about pushing yet another element on astack 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 memberfunction if the precondition was valid on entry to that function. A class is implementedcorrectly if post-conditions are never false. For example, after pushing an element on thestack, we know that isempty() must necessarily hold. This is a post-condition of the pushoperation.What are the conditions that have to be met for a condition to be an invariant ofthe 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); © IT Engineering Portal : www.itportal.in 40
  • 41. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.INconst 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]; // fineHere data[3] yields an Array1D object and the operator [] invocation on that object yieldsthe float in position(3,6) of the original two dimensional array. Clients of the Array2Dclass need not be aware of the presence of the Array1D class. Objects of this latter classstand for one-dimensional array objects that, conceptually, do not exist for clients ofArray2D. 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 conceptualmodel used by the clients of Array2D. In the above example, Array1D is a proxy class. Itsinstances 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 independentof, or orthogonal to each other. Orthogonal in the sense means that two classes operatein different dimensions and do not interfere with each other in any way. The samederived 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* 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 servicesinherited 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. Acontainer class acts as a generic holder. A container class has a predefined behavior anda well-known interface. A container class is a supporting class whose purpose is to hidethe topology used for maintaining the list of objects in memory. When a container class © IT Engineering Portal : www.itportal.in 41
  • 42. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.INcontains 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 iscalled 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;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; © IT Engineering Portal : www.itportal.in 42
  • 43. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.IN{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;}return head;}What is polymorphism?Polymorphism is the idea that a base class can be inherited by several classes. A baseclass pointer can point to its child class and a base class array can store different childclass 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 secondone goes at 1 nodes each time. If there is a cycle, the one that goes 2 nodes each time willeventually meet the one that goes slower. If that is the case, then you will know thelinked-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 fromthe C-Shell, just a return prompt if you are from the Bourne shell, and a 5 digitrandom numbers if you are from the Korn shell. You could also do a ps -l and lookfor 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 iffor all functional dependencies in F+ of the form a->b, where a and b is a subset ofR, 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 © IT Engineering Portal : www.itportal.in 43
  • 44. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.INWhat 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 declarationWrite a Struct Time where integer m, h, s are its membersstruct Time{int m;int h;int s;};How do you traverse a Btree in Backward in-order?Process the node in the right subtreeProcess the rootProcess the node in the left subtreeWhat is the two main roles of Operating System?As a resource managerAs a virtual machineIn the derived class, which data member of the base class are visible?In the public and protected sections.C++ programming on UNIXCould you tell something about the Unix System Kernel?The kernel is the heart of the UNIX openrating system, it’s reponsible for controllingthe computer’s resouces and scheduling user jobs so that each one gets its fairshare of resources.What are each of the standard files and what are they normally associatedwith?They are the standard input file, the standard output file and the standard errorfile. The first is usually associated with the keyboard, the second and third areusually associated with the terminal screen.Detemine the code below, tell me exectly how many times is the operationsum++ performed ?for ( i = 0; i < 100; i++ )for ( j = 100; j > 100 - i; j–)sum++; © IT Engineering Portal : www.itportal.in 44
  • 45. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.IN(99 * 100)/2 = 4950The sum++ is performed 4950 times.Give 4 examples which belongs application layer in TCP/IP architecture?FTP, TELNET, HTTP and TFTPWhat’s the meaning of ARP in TCP/IP?The "ARP" stands for Address Resolution Protocol. The ARP standard defines twobasic message types: a request and a response. a request message contains an IPaddress and requests the corresponding hardware address; a replay contains boththe 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 onlycompiling the portion of the program that has been changed.A Makefile is the file and make uses to determine what rules to apply. make isuseful for far more than compiling programs.What is deadlock?Deadlock is a situation when two or more processes prevent each other fromrunning. Example: if T1 is holding x and waiting for y to be free and T2 holding yand waiting for x to be free deadlock happens.What is semaphore?Semaphore is a special variable, it has two methods: up and down. Semaphoreperforms atomic operations, which means ones a semaphore is called it can not beinturrupted.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 otherthread 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 canbe done in C.Name some major differences between C++ and Java.C++ has pointers; Java does not. Java is platform-independent; C++ is not. Javahas garbage collection; C++ does not. Java does have pointers. In fact all variablesin Java are pointers. The difference is that Java does not allow you to manipulatethe addresses of the pointer © IT Engineering Portal : www.itportal.in 45
  • 46. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.INC++ Networking Interview Questions and AnswersWhat 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 structureWrite 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 are1) Analysis and specification of the task2) Design of the algorithms and data structures3) Implementation (coding)4) Testing5) Maintenance and evolution of the system6) ObsolescenceWhat is the difference between a Java application and a Java applet?The difference between a Java application and a Java applet is that a Javaapplication is a program that can be executed using the Java interpeter, and aJAVA applet can be transfered to different networks and executed by using a webbrowser (transferable to the WWW).Name 7 layers of the OSI Reference Model?-Application layer-Presentation layer-Session layer-Transport layer-Network layer-Data Link layer-Physical layer © IT Engineering Portal : www.itportal.in 46
  • 47. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.INC++ Algorithm Interview Questions and AnswersWhat are the advantages and disadvantages of B-star trees over Binary trees?Answer1B-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.Answer2The major difference between B-tree and binary tres is that B-tree is a external datastructure and binary tree is a main memory data structure. The computationalcomplexity of binary tree is counted by the number of comparison operations ateach node, while the computational complexity of B-tree is determined by the diskI/O, that is, the number of node that will be loaded from disk to main memory. Thecomparision of the different values in one node is not counted.Write the psuedo code for the Depth first Search.dfs(G, v) //OUTLINEMark 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, andbacktrack from w to v. Otherwise:"Check" vw without visiting w. Mark v as "finished".Describe one simple rehashing policy.The simplest rehashing policy is linear probing. Suppose a key K hashes to locationi. Suppose other key occupies H[i]. The following function is used to generatealternative locations:rehash(j) = (j + 1) mod hwhere 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 atone end, called the top. This updating policy is called last in, first out (LIFO). It isuseful 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 © IT Engineering Portal : www.itportal.in 47
  • 48. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.INthe 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 halfthe numner of frames that could be distinguished by the sequence number, so atmost 4 frames can be transmitted at a time. © IT Engineering Portal : www.itportal.in 48
  • 49. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.IN Java Interview Questions & Answers © IT Engineering Portal : www.itportal.in 49
  • 50. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.INJava Interview Questions and AnswersWhat is Collection API ?The Collection API is a set of classes and interfaces that support operation oncollections 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 andTreeMap.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 aCollection.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 otherclass. Interfaces are limited to public methods and constants with noimplementation. Abstract classes can have a partial implementation, protectedparts, static methods, etc.A Class may implement several interfaces. But in case of abstract class, a class mayextend only one abstract class. Interfaces are slow as it requires extra indirection toto 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 cantbe instantiated.Example of Abstract class:abstract class testAbstractClass {protected String myString;public String getMyString() {return myString;}public abstract string anyAbstractFunction();}How to define an Interface in Java ?In Java Interface defines the methods but does not implement them. Interface caninclude constants. A class that implements the interfaces is bound to implement allthe methods defined in Interface.Emaple of Interface:public interface sampleInterface {public void functionOne(); © IT Engineering Portal : www.itportal.in 50
  • 51. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.INpublic long CONSTANT_ONE = 1000;}If a class is located in a package, what do you need to change in the OSenvironment to be able to use it?You need to add a directory or a jar file that contains the package directories to theCLASSPATH environment variable. Lets say a class Employee belongs to a packagecom.xyz.hr; and is located in the file c:devcomxyzhrEmployee.java. In thiscase, youd need to add c:dev to the variable CLASSPATH. If this class contains themethod main(), you could test it from a command prompt window as follows:c:>java com.xyz.hr.EmployeeHow many methods in the Serializable interface?There is no method in the Serializable interface. The Serializable interface acts as amarker, 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 thesetwo methods in order to make your class externalizable. These two methods arereadExternal() and writeExternal().What is the difference between Serializalble and Externalizable interface?When you use Serializable interface, your class is serialized automatically bydefault. But you can override writeObject() and readObject() two methods to controlmore complex object serailization process. When you use Externalizable interface,you have a complete control over your classs serialization process.What is a transient variable in Java?A transient variable is a variable that may not be serialized. If you dont want somefield 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 anObservable object is updated, it invokes the update() method of each of its observersto notify the observers that it has changed state. The Observer interface isimplemented by objects that observe Observable objects.What is Java?Java is an object-oriented programming language developed initially by JamesGosling and colleagues at Sun Microsystems. The language, initially called Oak(named after the oak trees outside Goslings office), was intended to replace C++,although the feature set better resembles that of Objective C. Java should not be © IT Engineering Portal : www.itportal.in 51
  • 52. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.INconfused 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 trickquestion because the word "virtual" is not part of the naming convention in Java (asit is in C++, C-sharp and VB.NET), so this would be a foreign concept for someonewho has only coded in Java. Virtual functions or virtual methods are functions ormethods 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 themap 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 mapwould be seen on both maps, because the clone of Map is a shallow copy. So Jackmade a wrong decision.What is more advisable to create a thread, by implementing a Runnableinterface or by extending Thread class?Strategically speaking, threads created by implementing Runnable interface aremore advisable. If you create a thread by extending a thread class, you cannotextend 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 followingthings 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 suchexception 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. Forexample,class Test {static {System.loadLibrary("path-to-library-file");} © IT Engineering Portal : www.itportal.in 52
  • 53. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.IN....}When you call new Test(), the static block will be called first before any initializationhappens. Note that the static block position may matter.How could Java classes direct program messages to the system console, buterror messages, say to a file?The class System has a variable out that represents the standard output, and thevariable err that represents the standard error device. By default, they both point atthe 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);Whats the difference between an interface and an abstract class?An abstract class may contain code in method bodies, which is not allowed in aninterface. With abstract classes, you have to inherit your class from it and Javadoes not allow multiple inheritance. On the other hand, you can implementmultiple 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 andDialog classes.What do you understand by Synchronization?Synchronization is a process of controlling the access of shared resources by themultiple threads in such a manner that only one thread can access one resource ata time. In non synchronized multithreaded application, it is possible for one threadto modify a shared object while another thread is in the process of using orupdating the objects 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 theaccess of multiple threads to shared resources. Without synchronization, it ispossible for one thread to modify a shared object while another thread is in theprocess of using or updating that objects value. This often causes dirty data andleads to significant errors. © IT Engineering Portal : www.itportal.in 53
  • 54. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.INWhat are synchronized methods and synchronized statements?Synchronized methods are methods that are used to control access to a method oran object. A thread only executes a synchronized method after it has acquired thelock for the methods object or class. Synchronized statements are similar tosynchronized methods. A synchronized statement can only be executed after athread has acquired the lock for the object or class referenced in the synchronizedstatement.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 onIO, by unsuccessfully attempting to acquire an objects lock, or by invoking anobjects 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 classs Classobject.Whats 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 allowthe component to display normally.Whats the difference between J2SDK 1.5 and J2SDK 5.0?Theres no difference, Sun Microsystems just re-branded this version.What would you use to compare two String variables - the operator == orthe method equals()?Id use the method equals() to compare the values of the Strings and the == to checkif 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.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 systems task scheduler allocates execution time to multiple tasks.By quickly switching between executing tasks, it creates the impression that tasksexecute sequentially.How to create a thread in a program?You have two ways to do so. First, making your class "extends" Thread class. © IT Engineering Portal : www.itportal.in 54
  • 55. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.INSecond, 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 lockedobject 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 exclusivelyaccess to it?Yes. Use Thread.currentThread() method to track the accessing thread.Does it matter in what order catch statements for FileNotFoundExceptionand IOExceptipon are written?Yes, it does. The FileNoFoundException is inherited from the IOException.Exceptions subclasses have to be caught first.What invokes a threads run() method?After a thread is started, via its start() method of the Thread class, the JVM invokesthe threads 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 forthreads to communicate each other.What are the high-level thread states?The high-level thread states are ready, running, waiting, and dead.What is the difference between yielding and sleeping?When a task invokes its yield() method, it returns to the ready state. When a taskinvokes 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 statementand is unable to acquire an objects lock, it enters the waiting state until the lockbecomes 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 doesnt. Threads typicallyshare the heap belonging to their parent process. For instance, a JVM runs in asingle process in the host O/S. Threads in the JVM share the heap belonging tothat process; thats why several threads may access the same object. Typically, eventhough they share a common heap, threads have their own stack space. This is howone threads invocation of a method is kept separate from anothers. This is all agross oversimplification, but its accurate enough at a high level. Lots of detailsdiffer between operating systems. Process vs. Thread A program vs. similar to asequential program an run on its own vs. Cannot run on its own Unit of allocation © IT Engineering Portal : www.itportal.in 55
  • 56. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.INvs. Unit of execution Have its own memory space vs. Share with others Eachprocess 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 tocontext switch More secure. One process cannot corrupt another process vs. Lesssecure. A thread can write the memory used by another threadCan an inner class declared inside of a method access local variables of thismethod?Its possible if these variables are final.What can go wrong if you replace &emp;&emp; with &emp; in the followingcode: 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 objectsWhat modifiers may be used with an inner class that is a member of anouter 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 samepackage 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-8characters?Unicode requires 16 bits and ASCII require 7 bits. Although the ASCII character setuses only 7 bits, it is usually represented as 8 bits. UTF-8 represents charactersusing 8, 16, and 18 bit patterns. UTF-16 uses 16-bit and larger bit patterns.Whats 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 ofmemory?No, it doesnt. It is possible for programs to use up memory resources faster thanthey are garbage collected. It is also possible for programs to create objects that arenot subject to garbage collection. © IT Engineering Portal : www.itportal.in 56
  • 57. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.INWhat is the difference between preemptive scheduling and time slicing?Under preemptive scheduling, the highest priority task executes until it enters thewaiting or dead states or a higher priority task comes into existence. Under timeslicing, a task executes for a predefined slice of time and then reenters the pool ofready tasks. The scheduler then determines which task should execute next, basedon priority and other factors. Name Component subclasses that support painting ?The Canvas, Frame, Panel, and Applet classes support painting.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 extendinga class?An anonymous class may implement an interface or extend a superclass, but may not bedeclared to do both.What is the purpose of finalization?The purpose of finalization is to give an unreachable object the opportunity to perform anycleanup 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 intotal.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 theoperation.What is the numeric promotion?Numeric promotion is used with both unary and binary bitwise operators. This means © IT Engineering Portal : www.itportal.in 57
  • 58. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.INthat byte, char, and short values are converted to int values before a bitwise operator isapplied.If a binary bitwise operator has one long operand, the other operand is converted to along value.The type of the result of a bitwise operation is the type to which the operands have beenpromoted. 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, bitwiseoperations always yield the same result, even when run on machines that use radicallydifferent CPUs.What is the difference between the Boolean & operator and the && operator?If an expression involving the Boolean & operator is evaluated, both operands areevaluated. Then the & operator is applied to the operand. When an expression involvingthe && operator is evaluated, the first operand is evaluated. If the first operand returns avalue of true then the second operand is evaluated. The && operator is then applied tothe first and second operands. If the first operand evaluates to false, the evaluation of thesecond operand is skipped.Operator & has no chance to skip both sides evaluation and && operator does. If askedwhy, give details as above.When is the ArithmeticException throwQuestion: What is the GregorianCalendarclass?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, justwrite super(); in the first line of the subclasss constructor.What is the Properties class?The properties class is a subclass of Hashtable that can be read from or written to astream. It also provides the capability to specify a set of default values to be used.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. © IT Engineering Portal : www.itportal.in 58
  • 59. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.INWhat 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 ornot 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 particulargeographic, political, or cultural region.What is an abstract method?An abstract method is a method whose implementation is deferred to a subclass. Or, amethod that has no implementation.What is the difference between interface and abstract class?interface contains methods that must be abstract; abstract class may contain concretemethods. interface contains variables that must be static and final; abstract class may containnon-final and final variables. members in an interface are public by default, abstract classmay contain non-public members. interface is used to "implements"; whereas abstract classis used to "extends". interface can be used to achieve multiple inheritance; abstract class canbe used as a single inheritance. interface can "extends" another interface, abstract class can"extends" another class and "implements" multiple interfaces. interface is absolutelyabstract; abstract class can be invoked if a main() exists. interface is more flexible thanabstract 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 anddoesnt apply to an object or even require that any objects of the class have been instantiated.What is a protected method?A protected method is a method that can be accessed by any method in its package andinherited 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 theclasss outer class. A static inner class does not have any object instances.What is an objects lock and which objects have locks?An objects lock is a mechanism that is used by multiple threads to obtain synchronizedaccess to the object. A thread may execute a synchronized method of an object only afterit has acquired the objects lock. All objects and classes have locks. A classs lock isacquired on the classs 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 thereferenced interface. © IT Engineering Portal : www.itportal.in 59
  • 60. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.INWhat is the difference between a Window and a Frame?The Frame class extends Window to define a main application window that can have amenu bar.What is the difference between a Window and a Frame?Heavy weight components like Abstract Window Toolkit (AWT), depend on the localwindowing toolkit. For example, java.awt.Button is a heavy weight component, when it isrunning on the Java platform for Unix platform, it maps to a real Motif button. In thisrelationship, the Motif button is called the peer to the java.awt.Button. If you create twoButtons, two peers and hence two Motif Buttons are also created. The Java platformcommunicates with the Motif Buttons using the Java Native Interface. For each andevery component added to the application, there is an additional overhead tied to thelocal 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 andJWindow are lightweight components.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 asascent and descent, of a Font objectWhat is the difference between the Reader/Writer class hierarchy and theInputStream/OutputStream class hierarchy?The Reader/Writer class hierarchy is character-oriented, and theInputStream/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 beinitiated. It takes the Exception object to be thrown as argument. Theexception will be caught by an immediately encompassing try-catchconstruction or propagated further up the calling hierarchy.The throws keyword is a modifier of a method that designates thatexceptions may come out of the method, either by virtue of the methodthrowing the exception itself or because it fails to catch suchexceptions that a method it calls may throw.If a class is declared without any access modifiers, where may the class beaccessed? © IT Engineering Portal : www.itportal.in 60
  • 61. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.INA class that is declared without any access modifiers is said to have packageor friendly access. This means that the class can only be accessed by otherclasses 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 keyswith values.Does a class inherit the constructors of its super class?A class does not inherit constructors from any of its superclasses.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 objects 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, theelements are of different sizes and may occupy more than one row or column of thegrid. In addition, the rows and columns may have different sizes.What advantage do Javas layout managers provide over traditionalwindowing systems?Java uses layout managers to lay out components in a consistent manneracross all windowing platforms. Since Javas layout managers arent tied toabsolute sizing and positioning, they are able to accommodate platform-specific differences among windowing systems.What are the problems faced by Java programmers who dont use layoutmanagers?Without layout managers, Java programmers are faced with determining howtheir GUI will be displayed across multiple windowing systems and finding acommon sizing and positioning that will work within the constraints imposed byeach 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 withspecific instances of a class. Non-static variables take on unique values witheach object instance. © IT Engineering Portal : www.itportal.in 61
  • 62. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.INWhat 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 anddirectories 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. Theoverriding method may not limit the access of the method it overrides. The overridingmethod 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 castingbetween object references. Casting between numeric types is used to convert largervalues, such as double values, to smaller values, such as byte values. Casting betweenobject references is used to refer to an object by a compatible class, interface, or arraytype reference.Explain the usage of the keyword transient?This keyword indicates that the value of this member variable does not have to be serializedwith the object. When the class will be de-serialized, this variable will be initialized with adefault 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 superclassconstructor.How is it possible for two String objects with identical values not to be equalunder the == operator? How are this() and super() used with constructors?The == operator compares two objects to determine if they are the same objects inmemory. It is possible for two String objects to have the same value, but located indifferent areas of memory.What is an IO filter?An IO filter is an object that reads from one stream and writes to another, usuallyaltering the data in some way as it is passed from one stream to another. © IT Engineering Portal : www.itportal.in 62
  • 63. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.INWhat is the Set interface?The Set interface provides methods for accessing the elements of a finite mathematicalset. Sets do not allow duplicate elements.How can you force garbage collection?You cant force GC, but could request it by calling System.gc(). JVM does not guaranteethat 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. TheenableEvents() 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. TheRandomAccessFile class provides the methods needed to directly access data containedin any part of a file.What interface must an object implement before it can be written to a stream asan object?An object must implement the Serializable or Externalizable interface before it can bewritten 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 bya program to tailor the programs appearance to the particular locale in which it is beingrun.How do you know if an explicit object casting is needed?If you assign a superclass object to a variable of a subclasss data type, you need to doexplicit casting. For example:Object a; Customer b; b = (Customer) a;When you assign a subclass to a variable having a supeclass type, the casting isperformed 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 tocreate a separate name space for groups of classes and interfaces. Packages are alsoused to organize related classes and interfaces into a single API unit and to controlaccessibility 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 © IT Engineering Portal : www.itportal.in 63
  • 64. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.INclass is used to represent the classes and interfaces that are loaded by a Javaprogram.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 alsohelps resolve naming conflicts when different packages have classes with the samenames. Packages access level also allows you to protect data from being used by thenon-authorized classes.Does the code in finally block get executed if there is an exception and areturn statement in a catch block?If an exception occurs and there is a return statement in catch block, the finallyblock is still executed. The finally block will not be executed when theSystem.exit(1) statement is executed earlier or the system shut down earlier orthe 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.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 determinewhere components should go as a function of the size of the container.How the object oriented approach helps us keep complexity of softwaredevelopment under control?We can discuss such issue from the following aspects:Objects allow procedures to be encapsulated with their data to reduce potentialinterference.Inheritance allows well-tested procedures to be reused and enables changes tomake once and have effect in all relevant places.The well-defined separations of interface and implementation allow constraintsto be imposed on inheriting classes while still allowing the flexibility ofoverriding and overloading.What is polymorphism?Polymorphism means "having many forms". It allows methods (may bevariables) to be written that neednt be concerned about the specifics of theobjects they will be applied to. That is, the method can be specified at a higherlevel of abstraction and can be counted on to work even on objects of un-conceived classes. © IT Engineering Portal : www.itportal.in 64
  • 65. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.INWhat is design by contract?The design by contract specifies the obligations of a method to any othermethods that may use its services and also theirs to it. For example, thepreconditions specify what the method required to be true when the method iscalled. Hence making sure that preconditions are. Similarly, postconditionsspecify what must be true when the method is finished, thus the called methodhas 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 usedto make such contracts.What are use cases?A use case describes a situation that a program might encounter and whatbehavior the program should exhibit in that circumstance. It is part of theanalysis of a program. The collection of use cases should, ideally, anticipate allthe standard circumstances and many of the extraordinary circumstancespossible 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 scalabilitydescribes how an application behaves as its workload and available computingresources increase.What is the benefit of subclass?Generally: The sub class inherits all the public methods and theimplementation.The sub class inherits all the protected methods and their implementation.The sub class inherits all the default(non-access modifier) methods and theirimplementation.The sub class also inherits all the public, protected and default membervariables 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 cutby calling aboutButton.setMnemonic(A), so the user may be able to use Alt+Ato 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 fieldmember and println is a built-in overloaded method in the out object. © IT Engineering Portal : www.itportal.in 65
  • 66. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.INCan you write a Java class that could be used both as an applet as well asan 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() whichreturns an instance of the Calender class.No! You cannot make an instance of an abstract class. An abstract class has to besub-classed. If you have an abstract class and you want to use a method which hasbeen implemented, you may need to subclass that abstract class, instantiate yoursubclass and then call that method.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 isnecessary to ask back before you give an answer. Ask if variables a and b have beendeclared or initialized. If the answer is yes. You can say that the syntax is wrong. Ifthe statement is rewritten as: xWhat 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 Javaplatform 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 andprogrammers feel easier to deal with reference types without pointers. This is whyJava and C-sharp shine.Parsers? DOM vs SAX parserParsers are fundamental xml components, a bridge between XML documents andapplications that process that XML. The parser is responsible for handling xmlsyntax, checking the contents of the document against constraints established in aDTD or Schema.DOM1. Tree of nodes2. Memory: Occupies more memory, preffered for small XML documents3. Slower at runtime4. Stored as objects5. Programmatically easy6. Ease of navigationSAX1. Sequence of events2. Doesnt use any memory preferred for large documents3. Faster at runtime4. Objects are to be created © IT Engineering Portal : www.itportal.in 66
  • 67. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.IN5. Need to write code for creating objects6. Backward navigation is not possible as it sequentially processes the documentCan 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 shallowcopy 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 changedafter they are created, but they can be shared. Once you change a string, youactually 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 superclass, but can "implements" many interfaces; that doesnt mean the multipleinheritance is not possible. You may use interfaces to make inheritance work foryou. Or you may need to work around. For example, if you cannot get a featurefrom a class because your class has a super class already, you may get that classsfeature by declaring it as a member field or getting an instance of that class. So theanswer is that multiple inheritance in Java is possible.Whats 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.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 asatomic.(Some JVM might treat reads and writes of data of 64 bits or less as atomic infuture) For long or double variable, programmers should take care in multi-threadingenvironment. Either put these variables in a synchronized method or block, or declarethem volatile. © IT Engineering Portal : www.itportal.in 67
  • 68. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.INThis class (IncrementImpl) will be used by various threads concurrently; canyou 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. Theincrement() method is synchronized, but the getCounter() should be synchronized too.Otherwise the Java run-time system will not guarantee the data integrity and the raceconditions will occur. The famous producer/consumer example listed at Suns threadtutorial site will tell more.one of solutionspublic 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 thesubclass too clustering and sometimes error-prone when dynamic overriding or dynamicoverloading in some situation. In addition, the inheritance may make peers hardlyunderstand your code if they dont know how your super-class acts and add learningcurve to the process of development.Usually, when you want to use a functionality of a class, you may use subclass to inheritsuch function or use an instance of this class in your class. Which is better, depends onyour 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 aninstance of the class, actually you get every function available from this class, but youmay lose the dynamic features of OOPTwo methods have key words static synchronized and synchronized separately.What is the difference between them? © IT Engineering Portal : www.itportal.in 68
  • 69. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.INBoth 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 classitself 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 instancemethod belongs to its object. Every instance of the class gets its own copy of its instancemethod.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 asynchronized method. You are asked to tell the difference between instance and classmethod. Of course, your explanation to how synchronized keyword works doesnt 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)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 fromits subclasses. There is no way for private stuff to have a runtime overloading oroverriding (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 onthe syntax of "extends" and compare with C++, you may answer No and give explanationto support you. Or you may answer Yes. Recommend you to say Yes.Java DOES support multiple inheritance via interface implementation. Some people maynot think in this way. Give explanation to support your point.What is the difference between final, finally and finalize?Short answer:final - declares constantfinally - relates with exception handlingfinalize - helps in garbage collectionIf asked to give details, explain:final field, final method, final classtry/finally, try/catch/finallyprotected void finalize() in Object class © IT Engineering Portal : www.itportal.in 69
  • 70. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.INWhat kind of security tools are available in J2SE 5.0?There are three tools that can be used to protect application working within thescope 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.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 ofsourceArray 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 tocopy 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 andcopying all the old elements into the new array. But such copy is called shallowcopy or shallow clone because any changes to the object would be reflected in botharrays.When is the ArrayStoreException thrown?When copying elements between different arrays, if the source or destinationarguments are not arrays or their types are not compatible, an ArrayStoreExceptionwill be thrown.How to check two arrays to see if contents have the same types and containthe 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 multipleconstructors?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 memberclasses , a static member class has access to all static methods of the parent, ortop-level, class b) Member classes, the member class is instance specific and has © IT Engineering Portal : www.itportal.in 70
  • 71. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.INaccess to any and all methods and members, even the parents this reference c)Local classes, are declared within a block of code and are visible only within thatblock, just as any other method variable. d) Anonymous classes, is a local classthat has no nameIn which case would you choose a static inner class?Interesting one, static inner classes can access the outer classs protected andprivate fields. This is both a positive and a negative point for us since we can, inessence, violate the encapsulation of the outer class by mucking up the outerclasss protected and private fields. The only proper use of that capability is to writewhite-box tests of the class -- since we can induce cases that might be very hard toinduce via normal black-box tests (which dont have access to the internal state ofthe object). Second advantage,if I can say, is that, we can this static concept toimpose restriction on the inner class. Again as discussed in earlier point, an Innerclass has access to all the public, private and protected members of the parentclass. Suppose you want to restrict the access even to inner class, how would yougo ahead? Making the inner class static enforces it to access only the public staticmembers of the outer class( Since, protected and private members are not supposedto be static and that static members can access only other static members). If it hasto access any non-static member, it has to create an instance of the outer classwhich leads to accessing only public members.What is weak reference in JavaA weak reference is one that does not prevent the referenced object from beinggarbage collected. You might use them to manage a HashMap to look up a cache ofobjects. A weak reference is a reference that does not keep the object it refers toalive. A weak reference is not counted as a reference in garbage collection. If theobject 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 asa constant which cannot be modified. finally is usually used to release all theresources utilized inside the try block. All the resources present in the finalizemethod will be garbage collected whenever GC is called. Though finally and finalizeseem to be for a similar task there is an interesting tweak here, usually I preferfinally than finalize unless it is unavoidable. This is because the code in finallyblock is guaranteed of execution irrespective of occurrence of exception, whileexecution of finalize is not guarenteed.finalize method is called by the garbagecollector on an object when the garbage collector determines that there are no morereferences to the object. Presumably the garbage collector will, like its civil servantnamesake, visit the heap on a regular basis to clean up resources that are no longerin use. Garbage collection exists to prevent programmers from calling delete. This isa wonderful feature. For example, if you cant call delete, then you cant accidentallycall delete twice on the same object. However, removing delete from the language isnot the same thing as automatically cleaning up. To add to it, Garbage collectionmight not ever run. If garbage collection runs at all, and an object is no longerreferenced, then that objects finalize will run. Also, across multiple objects, finalize © IT Engineering Portal : www.itportal.in 71
  • 72. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.INorder is not predictable. The correct approach to resource cleanup in Java languageprograms does not rely on finalize. Instead, you simply write explicit close methodsfor objects that wrap native resources. If you take this approach, you mustdocument that the close method exists and when it should be called. Callers of theobject must then remember to call close when they are finished with a resource.Whats the difference between the methods sleep() and wait()The code sleep(1000); puts thread aside for exactly one second. The codewait(1000), causes a wait of up to one second. A thread could stop waiting earlier ifit receives the notify() or notifyAll() call. The method wait() is defined in the classObject 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 memoryaddresses. Starting in Java 1.2, we can use java.util.Arrays.equals(a, b) to comparewhether 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, Thesemethods use the system ClassLoader to locate resources, which gives you strictercontrol of the resources used by the application.ArithmeticException?The ArithmeticException is thrown when integer is divided by zero or taking theremainder 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 mayexecute while the I/O Operation is performed.What is the output from System.out.println("Hello"+null);?HellonullWhat is synchronization and why is it important?With respect to multithreading, synchronization is the capability to control theaccess of multiple threads to shared resources. Without synchronization, it ispossible for one thread to modify a shared object while another thread is in the © IT Engineering Portal : www.itportal.in 72
  • 73. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.INprocess of using or updating that objects value. This often leads to significanterrors.Can a lock be acquired on a class?Yes, a lock can be acquired on a class. This lock is acquired on the classs Classobject.Whats 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 allowthe component to display normally.What method is used to specify a containers layout?The setLayout() method is used to specify a containers 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 oncollections of objects.Which characters may be used as the second character of an identifier, but notas the first character of an identifier?The digits 0 through 9 may not be used as the first character of an identifier but theymay 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 theoperation.What is the Vector class?The Vector class provides the capability to implement a growable array of objectsWhat modifiers may be used with an inner class that is a member of an outerclass? © IT Engineering Portal : www.itportal.in 73
  • 74. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.INA (non-local) inner class may be declared as public, protected, private, static, final, orabstract.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 havebeen shifted out.Which method of the Component class is used to set the position and size of acomponent?setBounds()How many bits are used to represent Unicode, ASCII, UTF-16, and UTF-8characters?Unicode requires 16 bits and ASCII require 7 bits. Although the ASCII character set usesonly 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 invokesits 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 ispossible for programs to use up memory resources faster than they are garbage collected. Itis 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 asource code file?A package statement must appear as the first line in a source code file (excluding blank linesand comments).Can an objects finalize() method be invoked while it is reachable?An objects finalize() method cannot be invoked by the garbage collector while the objectis still reachable. However, an objects finalize() method may be invoked by other objects. © IT Engineering Portal : www.itportal.in 74
  • 75. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.INWhat is the immediate superclass of the Applet class?PanelWhat is the difference between preemptive scheduling and time slicing?Under preemptive scheduling, the highest priority task executes until it enters the waiting ordead states or a higher priority task comes into existence. Under time slicing, a task executesfor a predefined slice of time and then reenters the pool of ready tasks. The scheduler thendetermines 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 inexpressions. Associatity determines whether an expression is evaluated left-to-right orright-to-leftWhen 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.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 musteither 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 thatmay be checked or unchecked. © IT Engineering Portal : www.itportal.in 75
  • 76. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.INWhat is a tasks priority and how is it used in scheduling?A tasks priority is an integer value that identifies the relative order in which it should beexecuted with respect to other tasks. The scheduler attempts to schedule higher prioritytasks 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 extendinga class?An anonymous class may implement an interface or extend a superclass, but may not bedeclared 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-delegationmodel defined?Most of the AWT-related events of the event-delegation model are defined in thejava.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? MenuItemWhat is the purpose of finalization?The purpose of finalization is to give an unreachable object the opportunity to perform anycleanup processing before the object is garbage collected.Which class is the immediate super class of the MenuComponent class.ObjectWhat invokes a threads run() method?After a thread is started, via its start() method or that of the Thread class, the JVM invokesthe threads 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 areevaluated. Then the & operator is applied to the operand. When an expression involvingthe && operator is evaluated, the first operand is evaluated. If the first operand returns avalue of true then the second operand is evaluated. The && operator is then applied to © IT Engineering Portal : www.itportal.in 76
  • 77. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.INthe first and second operands. If the first operand evaluates to false, the evaluation of thesecond operand is skipped.Name three subclasses of the Component class.Box.Filler, Button, Canvas, Checkbox, Choice, Container, Label, List, Scrollbar, orTextComponentWhat 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 andredisplayed?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 objects finalize() method be invoked by the garbagecollector?An objects 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?The finally clause is used to provide the capability to execute code no matter whether or notan exception is thrown or caught.What is the argument type of a programs main() method?A programs 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 particulargeographic, 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 andreturn control to the loop statement. © IT Engineering Portal : www.itportal.in 77
  • 78. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.INWhat must a class do to implement an interface?It must provide all of the methods in the interface and identify the interface in itsimplements clause.What method is invoked to cause an object to begin executing as a separatethread?The start() method of the Thread class is invoked to cause an object to begin executing as aseparate thread.Name two subclasses of the TextComponent class.TextField and TextAreaWhat 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, itenables 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 components design and itsuse. The other advantage of the event-delegation model is that it performs much better inapplications where many events are generated. This performance improvement is due to thefact 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?FrameHow are commas used in the initialization and iteration parts of a forstatement?Commas are used to separate multiple statements within the initialization and iterationparts 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 threadsto wait for a shared resource. When a thread executes an objects wait() method, it entersthe waiting state. It only enters the ready state after another thread invokes the objectsnotify() 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 withinthe file. A source code file may contain at most one public class or interface. If a publicclass or interface is defined within a source code file, then the source code file must takethe name of the public class or interface. If no public class or interface is defined within a © IT Engineering Portal : www.itportal.in 78
  • 79. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.INsource code file, then the file must take on a name that is different than its classes andinterfaces. 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.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 ofthe classs 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 objects lock and which objects have locks?An objects lock is a mechanism that is used by multiple threads to obtainsynchronized access to the object. A thread may execute a synchronized method ofan object only after it has acquired the objects lock. All objects and classes havelocks. A classs lock is acquired on the classs 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 ofdividing 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 implementsthe referenced interface. © IT Engineering Portal : www.itportal.in 79
  • 80. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.INWhat is the difference between a Window and a Frame?The Frame class extends Window to define a main application window that canhave a menu bar.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 begarbage 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 asascent 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 towardzero.What happens when a thread cannot acquire a lock on an object?If a thread attempts to execute a synchronized method or synchronized statementand is unable to acquire an objects lock, it enters the waiting state until the lockbecomes available.What is the difference between the Reader/Writer class hierarchy and theInputStream/OutputStream class hierarchy?The Reader/Writer class hierarchy is character-oriented, and theInputStream/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 beaccessed?A class that is declared without any access modifiers is said to have packageaccess. This means that the class can only be accessed by other classes andinterfaces that are defined within the same package.What is the SimpleTimeZone class?The SimpleTimeZone class provides support for a Gregorian calendar. © IT Engineering Portal : www.itportal.in 80
  • 81. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.INWhat is the Map interface?The Map interface replaces the JDK 1.1 Dictionary class and is used associate keyswith 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 statementsthat 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 ofcards.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 objects design.What is the relationship between clipping and repainting?When a window is repainted by the AWT painting thread, it sets the clipping regionsto 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 anevent handler for a particular kind of event. An event adapter provides a defaultimplementation of an event-listener interface.What restrictions are placed on the values of each case of a switchstatement? © IT Engineering Portal : www.itportal.in 81
  • 82. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.INDuring compilation, the values of each case of a switch statement must evaluate toa 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-delegationclass 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-listenerinterface 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 loopiteration should occur. A do statement checks at the end of a loop to see whetherthe next iteration of a loop should occur. The do statement will always execute thebody 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, theelements are of different sizes and may occupy more than one row or column of thegrid. In addition, the rows and columns may have different sizes.What advantage do Javas layout managers provide over traditionalwindowing systems?Java uses layout managers to lay out components in a consistent manner across allwindowing platforms. Since Javas layout managers arent tied to absolute sizingand positioning, they are able to accommodate platform-specific differences amongwindowing systems.What is the Collection interface?The Collection interface provides support for the implementation of a mathematicalbag - 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 © IT Engineering Portal : www.itportal.in 82
  • 83. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.INinstances of a class. Non-static variables take on unique values with each objectinstance.What is the difference between the paint() and repaint() methods?The paint() method supports painting via a Graphics object. The repaint() method isused 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 anddirectories of a local file system.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 systems task scheduler allocates execution time to multiple tasks.By quickly switching between executing tasks, it creates the impression that tasksexecute 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 areprovided.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 thethread of execution terminates or an exception occurs within the execution of thefinally clause.Which class is the immediate superclass of the Container class?ComponentIf 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 samepackage 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 ofan identifier?The non-Unicode letter characters $ and _ may appear as the first character of anidentifier © IT Engineering Portal : www.itportal.in 83
  • 84. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.INWhat restrictions are placed on method overloading?Two methods may not have the same name and argument list but different returntypes.What happens when you invoke a threads interrupt method while it issleeping or waiting?When a tasks interrupt() method is executed, the task enters the ready state. Thenext time the task enters the running state, an InterruptedException is thrown.What is the return type of a programs main() method?A programs main() method has a void return type.Name four Container classes.Window, Frame, Dialog, FileDialog, Panel, Applet, or ScrollPaneWhat 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 thelist of available choices. Only one item may be selected from a Choice. A List may bedisplayed in such a way that several List items are visible. A List supports theselection 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 variableis a variable that is declared local to a method.Under what conditions is an objects finalize() method invoked by thegarbage collector?The garbage collector invokes an objects finalize() method when it detects that theobject 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 asuperclass constructor.What is the relationship between a methods throws clause and theexceptions that can be thrown during the methods execution?A methods throws clause must declare any checked exceptions that are not caughtwithin 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? © IT Engineering Portal : www.itportal.in 84
  • 85. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.INThe JDK 1.02 event model uses an event inheritance or bubbling approach. In thismodel, components are required to handle their own events. If they do not handle aparticular event, the event is inherited by (or bubbled up to) the componentscontainer. The container then either handles the event or it is bubbled up to itscontainer and so on, until the highest-level container has been tried. In the event-delegation model, specific objects are designated as event handlers for GUIcomponents. These objects implement event-listener interfaces. The event-delegation model is more efficient than the event-inheritance model because iteliminates the processing required to support the bubbling of unhandled events.How is it possible for two String objects with identical values not to beequal under the == operator?The == operator compares two objects to determine if they are the same object inmemory. It is possible for two String objects to have the same value, but locatedindifferent 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 aclass, 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 thesquares of a grid.What an I/O filter?An I/O filter is an object that reads from one stream and writes to another, usuallyaltering 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 becomereachable 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. © IT Engineering Portal : www.itportal.in 85
  • 86. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.INWhat 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 particularevent. The enableEvents() method is used by objects that handle events byoverriding 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. TheRandomAccessFile class provides the methods needed to directly access datacontained 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 platforms default character encoding?If you are running Java on English Windows platforms, it is probably Cp1252. Ifyou 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.What interface must an object implement before it can be written to astream as an object?An object must implement the Serializable or Externalizable interface before it canbe 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 thevariables 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 nolonger 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. Theoverriding method may not limit the access of the method it overrides. The © IT Engineering Portal : www.itportal.in 86
  • 87. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.INoverriding method may not throw any exceptions that may not be thrown by theoverridden 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 threadsThreadGroup being invoked, which eventually results in the termination of theprogram 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 anArithmeticException?Integer / and % can result in the throwing of an ArithmeticException.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 onI/O, by unsuccessfully attempting to acquire an objects lock, or by invoking anobjects 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 beloaded by a program to tailor the programs appearance to the particular locale inwhich it is being run.What happens if a try-catch-finally statement does not have a catch clauseto 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) orresults in the programs termination.What is numeric promotion?Numeric promotion is the conversion of a smaller numeric type to a larger numerictype, so that integer and floating-point operations may take place. In numericalpromotion, byte, char, and short values are converted to int values. The int valuesare also converted to long values, if necessary. The long and float values areconverted 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. AScrollPane handles its own events and performs its own scrolling. © IT Engineering Portal : www.itportal.in 87
  • 88. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.INWhat 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 notbe 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.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 theincrement operation. The postfix form returns the current value all of theexpression 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 singlestatement 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 tocreate a separate name space for groups of classes and interfaces. Packages arealso used to organize related classes and interfaces into a single API unit and tocontrol 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 Classclass is used to represent the classes and interfaces that are loaded by a Javaprogram.How does a try statement determine which catch clause should be used tohandle an exception?When an exception is thrown within the body of a try statement, the catch clausesof the try statement are examined in the order in which they appear. The first catchclause that is capable of handling the exception is executed. The remaining catchclauses are ignored.Can an unreachable object become reachable again?An unreachable object may become reachable again. This can happen when theobjects finalize() method is invoked and the object performs an operation whichcauses it to become accessible to reachable objects. © IT Engineering Portal : www.itportal.in 88
  • 89. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.INWhen is an object subject to garbage collection?An object is subject to garbage collection when it becomes unreachable to theprogram 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 Threador implement the Runnable interface.What methods are used to get and set the text label displayed by a Buttonobject?getLabel() and setLabel()Which Component subclass is used for drawing and painting?CanvasWhat are the two basic ways in which classes that can be run as threadsmay be defined?A thread class may be declared as a subclass of Thread, or it may implement theRunnable interface.What are the problems faced by Java programmers who dont use layoutmanagers?Without layout managers, Java programmers are faced with determining how theirGUI will be displayed across multiple windowing systems and finding a commonsizing and positioning that will work within the constraints imposed by eachwindowing 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 Booleanexpression to decide which alternative should be executed. The switch statement isused to select among multiple alternatives. It uses an int expression to determinewhich alternative should be executed.Can there be an abstract class with no abstract methods in it?yes.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. © IT Engineering Portal : www.itportal.in 89
  • 90. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.INWhat is Externalizable?Externalizable is an Interface that extends Serializable Interface. And sends datainto 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 variablesI made my class Cloneable but I still get Cant access protected methodclone. 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() isimplement the Cloneable interface. Not so. Perhaps that was the intent at somepoint, but thats not the way it works currently. As it stands, you have to implementyour own public clone() method, even if it doesnt do anything special and just callssuper.clone().What are the different identifier states of a Thread?The different identifiers of a Thread are:R - Running or runnable threadS - Suspended threadCW - Thread waiting on a condition variableMW - Thread waiting on a monitor lockMS - Thread suspended waiting on a monitor lockWhat are some alternatives to inheritance?Delegation is an alternative to inheritance. Delegation means that you include aninstance of another class as an instance variable, and forward messages to theinstance. It is often safer than inheritance because it forces you to think about eachmessage you forward, because the instance is of a known class, rather than a newclass, and because it doesnt 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, itmakes you write more code, and it is harder to re-use (because it is not a subclass).Why isnt there operator overloading?Because C++ has proven by example that operator overloading makes code almostimpossible to maintain. In fact there very nearly wasnt even method overloading inJava, but it was thought that this was too useful for some very basic methods likeprint(). Note that some of the classes like DataOutputStream have unoverloadedmethods like writeInt() and writeByte(). © IT Engineering Portal : www.itportal.in 90
  • 91. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.INWhat does it mean that a method or field is "static"?Static variables and methods are instantiated only once per class. In other wordsthey are class variables, not instance variables. If you change the value of a staticvariable in a particular object, the value of that variable changes for all instances ofthat class.Static methods can be referenced with the name of the class rather than the nameof a particular object of the class (though that works too). Thats how librarymethods like System.out.println() work. out is a static field in the java.lang.Systemclass.Why do threads block on I/O?Threads block on i/o (that is enters the waiting state) so that other threads mayexecute 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 theaccess of multiple threads to shared resources. Without synchronization, it ispossible for one thread to modify a shared object while another thread is in theprocess of using or updating that objects value. This often leads to significanterrors.Is null a keyword?The null value is not a keyword.Which characters may be used as the second character of an identifier,butnot as the first character of an identifier?The digits 0 through 9 may not be used as the first character of an identifier butthey 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 ofthem. Using notify() is preferable (for efficiency) when only one blocked thread canbenefit from the change (for example, when freeing a buffer back into a pool).notifyAll() is necessary (for correctness) if multiple threads should resume (forexample, when releasing a "writer" lock on a file might permit all "readers" toresume).Why cant 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 letsyou abbreviate class names, but not get rid of them altogether. Thats just the wayit works, youll get used to it. Its really a lot safer this way.However, there is actually a little trick you can use in some cases that gets youwhat you want. If your top-level class doesnt need to inherit from anything else,make it inherit from java.lang.Math. That *does* bring all the methods into yourlocal name space. But you cant use this trick in an applet, because you have toinherit from java.awt.Applet. And actually, you cant use it on java.lang.Math at all,because Math is a "final" class which means it cant be extended. © IT Engineering Portal : www.itportal.in 91
  • 92. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.INWhy are there no global variables in Java?Global variables are considered bad form for a variety of reasons: Adding statevariables breaks referential transparency (you no longer can understand astatement or expression on its own: you need to understand it in the context of thesettings of the global variables). State variables lessen the cohesion of a program: you need to know more tounderstand how something works. A major point of Object-Oriented programmingis 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 wantto 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 reasonswith basic classes like String and Integer. It also allows the compiler to make someoptimizations, and makes thread safety a little easier to achieve. Methods may bedeclared 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 its initialized, and it must include an initializerstatement where its declared. For example,public final double c = 2.998;Its also possible to make a static field final to get the effect of C++s const statementor some uses of Cs #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 notactually implemented in the current class. It exists only to be overridden insubclasses. It has no body. For example,public abstract float price();Abstract methods may only be included in abstract classes. However, an abstractclass 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 itssuperclasses 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 its a software-onlyplatform that runs on top of other hardware-based platforms.The Java platform has three elements:Java programming languageThe Java Virtual Machine (Java VM)The Java Application Programming Interface (Java API) © IT Engineering Portal : www.itportal.in 92
  • 93. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.INWhat 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 providemany 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 groupedinto libraries of related classes and interfaces; these libraries are known aspackages.What is native code?The native code is code that after you compile it, the compiled code runs on aspecific hardware platform.Explain the user defined Exceptions?User defined Exceptions are the separate Exception classes defined by the user forspecific purposed. An user defined can created by simply sub-classing it to theException class. This allows custom exceptions to be generated (using throw) andcaught 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 bitslower than native code. However, smart compilers, well-tuned interpreters, andjust-in-time bytecode compilers can bring performance close to that of native codewithout threatening portability.Can main() method be overloaded?Yes. the main() method is a special method for a program entry. You can overloadmain() 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 persistenceby having its properties or fields and state information saved and restored to andfrom 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 andOptional Package API, and provides inductrial-strength database computingcapabilities. © IT Engineering Portal : www.itportal.in 93
  • 94. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.INNew Features in JDBC 2.0 Core API:Scrollable result sets- using new methods in the ResultSet interface allowsprogrammatically move the to particular row or to a position relative to its currentpositionJDBC 2.0 Core API provides the Batch Updates functionality to the javaapplications.Java applications can now use the ResultSet.updateXXX methods.New data types - interfaces mapping the SQL3 data typesCustom 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 fortime zones in date, time, and timestamp values.How you can force the garbage collection?Garbage collection automatic process and cant be forced.Explain garbage collection?Garbage collection is one of the most important feature of Java. Garbage collectionis also called automatic memory management as JVM automatically removes theunused variables/objects (value is null) from the memory. User program canntdirectly free the object from memory, instead it is the job of the garbage collector toautomatically free the objects that are no longer referenced by a program. Everyclass inherits finalize() method from java.lang.Object, the finalize() method is calledby garbage collector when it determines no more references to the object exists. InJava, it is good idea to explicitly assign null into a variable when no more in use. IJava on calling System.gc() and Runtime.gc(), JVM tries to recycle the unusedobjects, 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, Inheritanceand Encapsulation.Explain the Encapsulation principle.Encapsulation is a process of binding or wrapping the data and the codes thatoperates on the data into a single entity. This keeps the data safe from outsideinterface and misuse. One way to think about encapsulation is as a protectivewrapper that prevents code and data from being arbitrarily accessed by other codedefined outside the wrapper.Explain the Inheritance principle.Inheritance is the process by which one object acquires the properties of anotherobject.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 © IT Engineering Portal : www.itportal.in 94
  • 95. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.INtypes of actions. The specific action is determined by the exact nature of thesituation. The concept of polymorphism can be explained as "one interface, multiplemethods".Explain the different forms of Polymorphism.From a practical programming viewpoint, polymorphism exists in three distinctforms in Java:Method overloadingMethod overriding through inheritanceMethod overriding through the Java interfaceWhat are Access Specifiers available in Java?ccess specifiers are keywords that determines the type of access to the member of aclass. These are:PublicProtectedPrivateDefaultsDescribe the wrapper classes in Java.Wrapper class is wrapper around a primitive data type. An instance of a wrapperclass contains, or wraps, a primitive value of the corresponding type.Following table lists the primitive types and the corresponding wrapper classes:Primitive Wrapperboolean java.lang.Booleanbyte java.lang.Bytechar java.lang.Characterdouble java.lang.Doublefloat java.lang.Floatint java.lang.Integerlong java.lang.Longshort java.lang.Shortvoid java.lang.VoidQuestion: 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");elseSystem.out.println("Equal");} © IT Engineering Portal : www.itportal.in 95
  • 96. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.IN}What is the result?A. The output is “Equal”B. The output in “Not Equal”C. An error at " if (x = y)" causes compilation to fall.D. The program executes but no output is show on console.Answer: CUse the Externalizable interface when you need complete control over yourBeans serialization (for example, when writing and reading a specific fileformat).No. Earlier order is maintained.The superclass constructor runs before the subclass constructor. Thesubclasss version of the overridable method will be invoked before thesubclasss constructor has been invoked. If the subclasss overridablemethod depends on the proper initialization of the subclass (through thesubclass constructor), the method will most likely fail. Is that true?Yes. It is trueWhy are the interfaces more flexible than abstract classes?--An interface-defined type can be implemented by any class in a class hierarchyand can be extended by another interface. In contrast, an abstract-class-definedtype can be implemented only by classes that subclass the abstract class.--An interface-defined type can be used well in polymorphism. The so-calledinterface type vs. implementation types.--Abstract classes evolve more easily than interfaces. If you add a new concretemethod to an abstract class, the hierarchy system is still working. If you add amethod to an interface, the classes that rely on the interface will break whenrecompiled.--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. generics2. static imports3. annotations4. typesafe enums5. enhanced for loop6. autoboxing/unboxing7. varargs8. covariant return types © IT Engineering Portal : www.itportal.in 96
  • 97. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.INWhat is covariant return type?A covariant return type lets you override a superclass method with a return typethat subtypes the superclass methods return type. So we can use covariant returntypes 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 ChildParent 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 compileri = i + f; //errorThe compound assignment operators automatically include cast operations in theirbehaviors.What is externalization? Where is it useful?Use the Externalizable interface when you need complete control over your Beansserialization (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 © IT Engineering Portal : www.itportal.in 97
  • 98. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.INB5C nullD Print some junk charactersAnswer : DIt will print some junk characters to the output. Here it will not give any compiletime 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 itsdefaults.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]);}}A Error array not initializedB5C0D Print some junk charactersAnswer : 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 certaincapability.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 insidestatic 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 arejava programs are running inside this JVM only. It converts java byte code to OSspecific commands. In addition to governing the execution of an applications bytecodes, the virtual machine handles related tasks such as managing the systemsmemory, providing security against malicious code, and managing multiple threadsof program execution. © IT Engineering Portal : www.itportal.in 98
  • 99. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.INWhat 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 classClassLoader is an abstract class. Given the name of a class, a class loader shouldattempt to locate or generate data that constitutes a definition for the class. Atypical 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 createdautomatically 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 elementtype; if the element type is a primitive type, then the array class has no classloader.Applications implement subclasses of ClassLoader in order to extend the manner inwhich 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 andJ2EE service lookup as EJB (Enterprise JavaBean) Interview Questions - Home andJMS (Java Message Service) component factories. The Service Locator hides thelookup processs implementation details and complexity from clients. To improveapplication performance, Service Locator caches service objects to eliminateunnecessary JNDI (Java Naming and Directory Interface) activity that occurs in alookup operation.What is Session Facade pattern?Session facade is one design pattern that is often used while developing enterpriseapplications. It is implemented as a higher level component (i.e.: Session EJB), andit contains all the iteractions between low level components (i.e.: Entity EJB). Itthen 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 banksituation, where you have someone that would like to transfer money from oneaccount to another. In this type of scenario, the client has to check that the user isauthorized, get the status of the two accounts, check that there are enough moneyon the first one, and then call the transfer. The entire transfer has to be done in asingle transaction otherwise is something goes south, the situation has to berestored.As you can see, multiple server-side objects need to be accessed and possiblymodified. Multiple fine-grained invocations of Entity (or even Session) Beans addthe overhead of network calls, even multiple transaction. In other words, the risk isto have a solution that has a high network overhead, high coupling, poor reusabilityand mantainability.The best solution is then to wrap all the calls inside a Session Bean, so the clients © IT Engineering Portal : www.itportal.in 99
  • 100. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.INwill have a single point to access (that is the session bean) that will take care ofhandling all the rest.What is Data Access Object pattern?The Data Access Object (or DAO) pattern: separates a data resources clientinterface from its data access mechanisms adapts a specific data resources accessAPI to a generic client interfaceThe DAO pattern allows data access mechanisms to change independently of thecode 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 likea B2B exchange, a repository like an LDAP database, or a business service accessedvia CORBA Internet Inter-ORB Protocol (IIOP) or low-level sockets. The businesscomponent that relies on the DAO uses the simpler interface exposed by the DAOfor its clients. The DAO completely hides the data source implementation detailsfrom its clients. Because the interface exposed by the DAO to clients does notchange when the underlying data source implementation changes, this patternallows the DAO to adapt to different storage schemes without affecting its clients orbusiness components. Essentially, the DAO acts as an adapter between thecomponent and the data source.Can we make an EJB singleton?This is a debatable question, and for every answer we propose there can becontradictions. I propose 2 solutions of the same. Remember that EJBs aredistributed components and can be deployed on different JVMs in a Distributedenvironmenti) Follow the steps as given belowMake sure that your serviceLocator is deployed on only one JVM.In the serviceLocator create a HashTable/HashMap(You are the right judge tochoose between these two)When ever a request comes for an EJB to a serviceLocator, it first checks in theHashTable if an entry already exists in the table with key being the JNDI name ofEJB. If key is present and value is not null, return the existing reference, elselookup the EJB in JNDI as we do normally and add an entry into the Hashtablebefore returning it to the client. This makes sure that you maintain a singleton ofEJB.ii) In distributed environment our components/Java Objects would be running ondifferent JVMs. So the normal singleton code we write for maintaining singleinstance works fine for single JVM, but when the class could be loaded in multipleJVMs and Instantiated in multiple JVMs normal singleton code does not work.This is because the ClassLoaders being used in the different JVMs are differentfrom each other and there is no defined mechanism to check and compare what isloaded in another JVM. A solution could be(Not tested yet. Need your feedback onthis) 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 iscreated for the proposed class. This can be done easily. © IT Engineering Portal : www.itportal.in 100
  • 101. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.INHow can we make a class Singleton ?A) If the class is Serializableclass 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;}}B) If the class is NOT Serializableclass Singleton{private static Singleton instance;private Singleton() { }public static synchronized Singleton getInstance(){if (instance == null)instance = new Singleton();return instance; © IT Engineering Portal : www.itportal.in 101
  • 102. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.IN}/**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 isperformed on the Class and not on the Object, while in the case of a Non-staticblock/member, lock is applied on the Object and not on class. [Trail 2: There is aclass 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. Thatshow even if you create multiple objects of your class only one Class object is presentand all your objects are linked to this Class object. Even though one of your objectis GCed after some time, this object of Class is not GCed untill all the objectsassociated with it are GCed.This means that when ever you call a "static synchronized" block, JVM locks accessto 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 Classlevel members and those which are non-static are called as Instance levelmembers.Name few Garbage collection algorithms?Here they go:Mark and SweepReference countingTracing collectorsCopying collectorsHeap compactionMark-compact collectorsCan we force Garbage collection?java follows a philosophy of automatic garbage collection, you can suggest orencourage the JVM to perform garbage collection but you can not force it. Once avariable is no longer referenced by anything it is available for garbage collection.You can suggest garbage collection with System.gc(), but this does not guaranteewhen it will happen. Local variables in methods go out of scope when the method © IT Engineering Portal : www.itportal.in 102
  • 103. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.INexits. At this point the methods are eligible for garbage collection. Each time themethod 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 sendingmethod arguments. Those who feel why I added this simple question in this sectionwhile claiming to be maintaining only strong and interesting questions, go aheadand answer following questions.a)What is the out put of:import java.util.*;class TestCallByRefWithObject{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: © IT Engineering Portal : www.itportal.in 103
  • 104. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.INimport java.util.*;class TestCallByRefWithInt{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 theres a processwhich has spawned only one thread) in one JVM and a process in another and thatboth of them require same resources then both of them would take same time toexecute. But, when a program/Application is thread based(remember here therewill be multiple threads running for a single process) then definetly a thread basedappliation/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 criticalsection and allocates the mutex to another process.Before deallocating the ealier one, it stores the context(till what state did it executethat process) in registers. Now if this deallocated process has to come back andexecute as it has got the resource for which it was waiting, then it cant go intocritical section directly. CPU asks that process to follow scheduling algorithm. Sothis process has to wait again for its turn. While in the case of thread basedapplication, the application is still with CPU only that thread which requires someresource goes out, but its co threads(of same process/apllication) are still in the © IT Engineering Portal : www.itportal.in 104
  • 105. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.INcritical 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 isprocess based.Be sure that its not the competion between thread and process, its between anapplication 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 pointerin the running program. The most straightforward garbage collection algorithmssimply iterate over every reachable object. Any objects left over are then consideredgarbage.What are generations in Garbage Collection terminology? What is itsrelevance?Garbage Collectors make assumptions about how our application runs. Mostcommon assumption is that an object is most likely to die shortly after it wascreated: called infant mortality. This assumes that an object that has been aroundfor 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 certainperiod of time it is moved from one generation to another generations( say fromyoung -> tenured -> permanent). Hence GC will be run more frequently at theyoung generations and rarely at permanent generations. This reduces the overheadon GC and gives faster response time.What is a Throughput Collector?The throughput collector is a generational collector similar to the default collectorbut with multiple threads used to do the minor collection. The major collections areessentially 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. Thenumber of garbage collector threads can be controlled with a command line option.When to Use the Throughput Collector?Use the throughput collector when you want to improve the performance of yourapplication with larger numbers of processors. In the default collector garbagecollection is done by one thread, and therefore garbage collection adds to the serialexecution time of the application. The throughput collector uses multiple threads toexecute a minor collection and so reduces the serial execution time of theapplication. A typical situation is one in which the application has a large numberof threads allocating objects. In such an application it is often the case that a largeyoung generation is neededWhat is Aggressive Heap?The -XX:+AggressiveHeap option inspects the machine resources (size of memoryand number of processors) and attempts to set various parameters to be optimal forlong-running, memory allocation-intensive jobs. It was originally intended formachines with large amounts of memory and a large number of CPUs, but in theJ2SE platform, version 1.4.1 and later it has shown itself to be useful even on four © IT Engineering Portal : www.itportal.in 105
  • 106. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.INprocessor machines. With this option the throughput collector (-XX:+UseParallelGC)is used along with adaptive sizing (-XX:+UseAdaptiveSizePolicy). The physicalmemory on the machines must be at least 256MB before Aggressive Heap can beused.What is a Concurrent Low Pause Collector?The concurrent low pause collector is a generational collector similar to the defaultcollector. The tenured generation is collected concurrently with this collector. Thiscollector attempts to reduce the pause times needed to collect the tenuredgeneration. It uses a separate garbage collector thread to do parts of the majorcollection concurrently with the applications threads. The concurrent collector isenabled with the command line option -XX:+UseConcMarkSweepGC. For eachmajor collection the concurrent collector will pause all the application threads for abrief period at the beginning of the collection and toward the middle of thecollection. The second pause tends to be the longer of the two pauses and multiplethreads are used to do the collection work during that pause. The remainder of thecollection is done with a garbage collector thread that runs concurrently with theapplication. The minor collections are done in a manner similar to the defaultcollector, and multiple threads can optionally be used to do the minor collection.When to Use the Concurrent Low Pause Collector?Use the concurrent low pause collector if your application would benefit fromshorter garbage collector pauses and can afford to share processor resources withthe garbage collector when the application is running. Typically applications whichhave a relatively large set of long-lived data (a large tenured generation), and run onmachines 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 pausetime requirement. Optimal results have been observed for interactive applicationswith 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 defaultcollector. The minor collections are done with the same young generation collectoras the default collector. Do not use either -XX:+UseParallelGC or -XX:+UseParNewGC with this collector. The major collections are done incrementallyon the tenured generation. This collector (also known as the train collector) collectsportions of the tenured generation at each minor collection. The goal of theincremental collector is to avoid very long major collection pauses by doing portionsof the major collection work at each minor collection. The incremental collector willsometimes find that a non-incremental major collection (as is done in the defaultcollector) 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 tradelonger and more frequent young generation garbage collection pauses for shortertenured generation pauses. A typical situation is one in which a larger tenuredgeneration is required (lots of long-lived objects), a smaller young generation will © IT Engineering Portal : www.itportal.in 106
  • 107. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.INsuffice (most objects are short-lived and dont survive the young generationcollection), and only a single processor is available.How do you enable the concurrent garbage collector on Suns JVM?-Xconcgc options allows us to use concurrent garbage collector (1.2.2_07+)we canalso use -XX:+UseConcMarkSweepGC which is available beginning with J2SE 1.4.1.What is a platform?A platform is the hardware or software environment in which a program runs. Mostplatforms 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 cant be serialize. For example if a variable is declared astransient in a Serializable class and the class is written to an ObjectStream, thevalue of the variable cant be written to the stream instead when the class isretrieved 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 thejava.io.Externalizable interface. As long as one class in a classs inheritancehierarchy 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 returntypes.Name Container classes.Window, Frame, Dialog, FileDialog, Panel, Applet, or ScrollPaneWhat 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. AScrollPane 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 makeRMI application get through firewall. In CS world, tunnelling means a way totransfer data.What is meant by "Abstract Interface"?First, an interface is abstract. That means you cannot have any implementation inan interface. All the methods declared in an interface are abstract methods orsignatures of the methods. © IT Engineering Portal : www.itportal.in 107
  • 108. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.INCan 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 berun in the specific platform, not cross-platform.Do not use the String contatenation operator in lengthy loops or otherplaces where performance could suffer. Is that true?Yes.What method is used to specify a containers layout?The setLayout() method is used to specify a containers 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 oncollections 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 andredisplayed?validate()Whats the difference between a queue and a stack?Stacks works by last-in-first-out rule (LIFO), while queues use the FIFO ruleWhat comes to mind when you hear about a young generation in Java?Garbage collection.You can create an abstract class that contains only abstract methods. Onthe other hand, you can create an interface that declares the samemethods. So can you use abstract classes instead of interfaces?Sometimes. But your class may be a descendent of another class and in this casethe interface is your only option. © IT Engineering Portal : www.itportal.in 108
  • 109. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.INWhat comes to mind when someone mentions a shallow copy in Java?Object cloning.If youre overriding the method equals() of an object, which other methodyou might also consider?hashCode()You are planning to do an indexed search in a list of objects. Which of thetwo Java collections should you use: ArrayList or LinkedList?ArrayListHow 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 memoryuse 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 whensome important event has happened. What Java technique would you use toimplement it?If these classes are threads Id consider notify() or notifyAll(). For regular classes youcan use the Observer interface.What access level do you need to specify in the class declaration to ensurethat only classes from the same directory can access it?You do not need to specify any access level, and Java will use a default packageaccess level.What is the difference between an Interface and an Abstract class?An abstract class can have instance methods that implement a default behavior. AnInterface can only declare constants and instance methods, but cannot implementdefault behavior and all methods are implicitly abstract. An interface has all publicmembers and no implementation. An abstract class is a class which may have theusual flavors of class members (private, protected, etc.), but has some abstractmethods.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 nolonger needed by a program so that their resources can be reclaimed and reused. AJava object is subject to garbage collection when it becomes unreachable to theprogram in which it is used.Describe synchronization in respect to multithreading.With respect to multithreading, synchronization is the capability to control theaccess of multiple threads to shared resources. Without synchonization, it ispossible for one thread to modify a shared variable while another thread is in the © IT Engineering Portal : www.itportal.in 109
  • 110. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.INprocess of using or updating same shared variable. This usually leads to significanterrors.Explain different way of using thread?The thread could be implemented by using runnable interface or by inheriting fromthe Thread class. The former is more advantageous, cause when you are going formultiple 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 thevalue. 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 isunsynchronized and permits nulls. (HashMap allows null values as key and valuewhereas Hashtable doesnt allow). HashMap does not guarantee that the order of themap will remain constant over time. HashMap is unsynchronized and Hashtable issynchronized.Difference between Vector and ArrayList?Vector is synchronized whereas arraylist is not.Difference between Swing and AWT?AWT are heavy-weight components. Swings are light-weight components. Henceswing 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 thatclass. It has the same name as the class itself, has no return type, and is invokedusing the new operator. A method is an ordinary member function of a class. It hasits own name, a return type (which may be void), and is invoked using the dotoperator.What is an Iterator?Some of the collection classes provide traversal of their contents via ajava.util.Iterator interface. This interface allows you to walk through a collection ofobjects, operating on each object in turn. Remember when using Iterators that theycontain a snapshot of the collection at the time the Iterator was obtained; generallyit is not advisable to modify the collection itself while traversing an Iterator.State the significance of public, private, protected, default modifiers bothsingly and in combination and state the effect of package relationships ondeclared items qualified by these modifiers.public : Public class is visible in other packages, field is visible everywhere (class © IT Engineering Portal : www.itportal.in 110
  • 111. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.INmust be public too) private : Private variables or methods may be used only by aninstance of the same class that declares the variable or method, A private featuremay only be accessed by the class that owns the feature. protected : Is available toall classes in the same package and also available to all subclasses of the class thatowns the protected feature. This access is provided even to subclasses that reside ina different package from the class that owns the protected feature. default :Whatyou get by default ie, without any access modifier (ie, public private or protected). Itmeans 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 itsconstructor), abstract class may contain static data. Any class with an abstractmethod is automatically abstract itself, and must be declared as such.A class may be declared abstract even if it has no abstract methods. This preventsit from being instantiated.What is static in java?Static means one per class, not one for each object no matter how many instance ofa class might exist. This means that you can use them without creating an instanceof a class. Static methods are implicitly final, because overriding is done based onthe type of the object, and static methods are attached to a class, not an object. Astatic method in a super class can be shadowed by another static method in asubclass, as long as the original method was not declared final. However, you cantoverride a static method with a no static method. In other words, you cant changea static method into an instance method in a subclass.What is final?A final class cant be extended ie., final class may not be subclassed. A final methodcant be overridden when its class is inherited. You cant change value of a finalvariable (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 mainmethod?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". © IT Engineering Portal : www.itportal.in 111
  • 112. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.INWhat 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 Stringarray of Main method will be empty or null?It is empty. But not null.How can one prove that the array is not null but empty using one line ofcode?Print args.length. It will print 0. That means it is empty. But if it would have beennull then it would have thrown a NullPointerException on attempting to printargs.length.Can an application have multiple classes having main method?Yes it is possible. While starting the application we mention the class name to berun. The JVM will look for the Main method only in the class whose name you havementioned. Hence there is not conflict amongst the multiple classes having mainmethod.Can I have multiple main methods in the same class?No the program fails to compile. The compiler says that the main method is alreadydefined 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 packagetwice at runtime?One can import the same package or same class multiple times. Neither compilernor JVM complains abt it. And the JVM will internally load the class only once nomatter 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), excludingclass RuntimeException and its subclasses. Making an exception checked forcesclient programmers to deal with the possibility that the exception will be thrown. eg,IOException thrown by java.io.FileInputStreams read() method Uncheckedexceptions are RuntimeException and any of its subclasses. Class Error and itssubclasses also are unchecked. With an unchecked exception, however, thecompiler doesnt force client programmers either to catch the exception or declare itin a throws clause. In fact, client programmers may not even know that theexception could be thrown. eg, StringIndexOutOfBoundsException thrown byStrings charAt() method Checked exceptions must be caught at compile time.Runtime exceptions do not need to be. Errors often cannot be. © IT Engineering Portal : www.itportal.in 112
  • 113. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.INWhat is Overriding?When a class defines a method using the same name, return type, and argumentsas a method in its superclass, the method in the class overrides the method in thesuperclass.When the method is invoked for an object of the class, it is the new definition of themethod that is called, and not the method definition from superclass. Methods maybe overridden to be more public, not more private.What are different types of inner classes?Nested top-level classes, Member classes, Local classes, Anonymous classesNested top-level classes- If you declare a class within a class and specify the staticmodifier, the compiler treats the class just like any other top-level class.Any class outside the declaring class accesses the nested class with the declaringclass name acting similarly to a package. eg, outer.inner. Top-level inner classesimplicitly have access only to static variables.There can also be inner interfaces. Allof these are of the nested top-level variety.Member classes - Member inner classes are just like other member methods andmember variables and access to the member class is restricted, just like methodsand variables. This means a public member class acts similarly to a nested top-levelclass. The primary difference between member classes and nested top-level classesis 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 tobe useful beyond the declaration block, it would need to implement a more publiclyavailable 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 levelfurther. As anonymous classes have no name, you cannot provide a constructor.Are the imports checked for validity at compile time? e.g. will the codecontaining an import such as java.lang.ABCD compile?Yes the imports are checked for the semantic validity at compile time. The codecontaining above line of import will not compile. It will throw an error saying,cannot resolve symbolsymbol : class ABCDlocation: package ioimport java.io.ABCD;Does importing a package imports the subpackages as well? e.g. Doesimporting com.MyTest.* also import com.MyTest.UnitTests.*?No you will have to import the subpackages explicitly. Importing com.MyTest.* willimport classes in the package MyTest only. It will not import any class in any of itssubpackage. © IT Engineering Portal : www.itportal.in 113
  • 114. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.INWhat is the difference between declaring a variable and defining avariable?In declaration we just mention the type of the variable and its name. We do notinitialize 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 instancevariable?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" orno modifier. If it does not have a modifier it is supposed to have a default access.If atop level class is declared as private the compiler will complain that the "modifierprivate 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 passedby value and so both the original reference and parameter copy both refer to thesame object .What is serialization?Serialization is a mechanism by which you can save the state of an object byconverting 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 interfaceSerializable. Then you pass the instance to the ObjectOutputStream which isconnected 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. Sowe do not implement any methods.How can I customize the serialization process? i.e. how can one have acontrol over the serialization process?Yes it is possible to have control over serialization process. The class shouldimplement Externalizable interface. This interface contains two methods namely © IT Engineering Portal : www.itportal.in 114
  • 115. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.INreadExternal and writeExternal. You should implement these methods and writethe 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 andwriteExternal. These methods give you a control over the serialization mechanism.Thus if your class implements this interface, you can customize the serializationprocess by implementing these methods.When you serialize an object, what happens to the object referencesincluded in the object?The serialization mechanism generates an object graph for serialization. Thus itdetermines whether the included object references are serializable or not. This is arecursive process. Thus when an object is serialized, all the included objects arealso 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 ofthe 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 writeto the stream. These are1. Serialization ignores static fields, because they are not part of ay particular statestate.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 thesize 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 executionwithout using any profiling tool?Read the system time just before the method is invoked and immediately aftermethod returns. Take the time difference, which will give you the time taken by amethod for execution.To put it in code... © IT Engineering Portal : www.itportal.in 115
  • 116. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.INlong 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 istaking zero milliseconds for execution. Try it on a method which is big enough, inthe 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 thecollection classes store objects and not primitive data types. And also the wrapperclasses provide many utility methods also. Because of these reasons we needwrapper classes. And since we create instances of these classes we can store themin any of the collection classes and pass them around as a collection. Also we canpass 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 ofeither wrong input data or because of wrong business logic etc. These are notchecked 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 OutOfMemoryerror. These JVM errors and you can not repair them at runtime. While exceptionsare conditions that occur because of bad input etc. e.g. FileNotFoundException willbe thrown if the specified file does not exist. Or a NullPointerException will takeplace if you try using a null reference. In most of the cases it is possible to recoverfrom an exception (probably by giving user a feedback for entering proper valuesetc.).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, whatshould I do?The class should extend from Exception class. Or you can extend your class fromsome more precise exception type also.If my class already extends from some other class what should I do if Iwant an instance of my class to be thrown as an exception object? © IT Engineering Portal : www.itportal.in 116
  • 117. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.INOne can not do anything in this scenario. Because Java does not allow multipleinheritance 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 Whenan exception is thrown from a code which is wrapped in a try block followed by oneor more catch blocks, a search is made for matching catch block. If a matching typeis found then that block will be invoked. If a matching type is not found then theexception moves up the method stack and reaches the caller method. Sameprocedure is repeated if the caller method is included in a try catch block. Thisprocess continues until a catch block handling the appropriate type of exception isfound. 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 theexceptions. and2. List the desired exceptions in the throws clause of the method and let the callerof the method handle those exceptions.What is the basic difference between the 2 approaches to exceptionhandling.1. try catch block and2. 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 withthe exception. This is fine if you are in a best position to decide should be done incase of an exception. Whereas if it is not the responsibility of the method to dealwith its own exceptions, then do not use this approach. In this case use the secondapproach. In the second approach we are forcing the caller of the method to catchthe exceptions, that the method is likely to throw. This is often the approach librarycreators 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.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 shouldbe followed by either a catch block OR a finally block. And whatever exceptions arelikely 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 stillexecute?Yes even if you write return as the last statement in the try block and no exceptionoccurs, the finally block will execute. The finally block will execute and then thecontrol return.If I write System.exit (0); at the end of the try block, will the finally blockstill execute? © IT Engineering Portal : www.itportal.in 117
  • 118. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.INNo 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 neverexecutes.How are Observer and Observable used?Objects that subclass the Observable class maintain a list of observers. When anObservable object is updated it invokes the update() method of each of its observersto notify the observers that it has changed state. The Observer interface isimplemented by objects that observe Observable objects.What is synchronization and why is it important?With respect to multithreading, synchronization is the capability to control theaccess of multiple threads to shared resources. Without synchronization, it ispossible for one thread to modify a shared object while another thread is in theprocess of using or updating that objects value. This often leads to significanterrors.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 typeallowed by the operation.Does garbage collection guarantee that a program will not run out ofmemory?Garbage collection does not guarantee that a program will not run out of memory. Itis possible for programs to use up memory resources faster than they are garbagecollected. It is also possible for programs to create objects that are not subject togarbage collection .What is the difference between preemptive scheduling and time slicing?Under preemptive scheduling, the highest priority task executes until it enters thewaiting or dead states or a higher priority task comes into existence. Under timeslicing, a task executes for a predefined slice of time and then reenters the pool ofready tasks. The scheduler then determines which task should execute next, basedon 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 toperform 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 particulargeographic, political, or cultural region. © IT Engineering Portal : www.itportal.in 118
  • 119. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.INWhat 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 loopiteration should occur. A do statement checks at the end of a loop to see whetherthe next iteration of a loop should occur. The do statement will always execute thebody 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 specificinstances of a class. Non-static variables take on unique values with each objectinstance.How are this() and super() used with constructors?This() is used to invoke a constructor of the same class. super() is used to invoke asuperclass constructor.What are synchronized methods and synchronized statements?Synchronized methods are methods that are used to control access to an object. Athread only executes a synchronized method after it has acquired the lock for themethods object or class. Synchronized statements are similar to synchronizedmethods. A synchronized statement can only be executed after a thread hasacquired the lock for the object or class referenced in the synchronized statement.What is daemon thread and which method is used to create the daemonthread?Daemon thread is a low priority thread which runs intermittently in the background 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 thesame virtual machine. If the applets are of the same class, they can communicatevia shared static variables. If the applets are of different classes, then each will needa reference to the same class with static variables. In any case the basic idea is topass the information back and forth through a static variable.An applet can also get references to all other applets on the same page using thegetApplets() method of java.applet.AppletContext. Once you get the reference to anapplet, you can communicate with it by using its public members.It is conceivable to have applets in different virtual machines that talk to a serversomewhere 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 : © IT Engineering Portal : www.itportal.in 119
  • 120. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.INClass.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();How does a try statement determine which catch clause should be used tohandle an exception?When an exception is thrown within the body of a try statement, the catch clausesof the try statement are examined in the order in which they appear. The first catchclause that is capable of handling the exceptionis executed. The remaining catchclauses are ignored.Can an unreachable object become reachable again?An unreachable object may become reachable again. This can happen when theobjects finalize() method is invoked and the object performs an operation whichcauses 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 Threador implement the Runnable interface.What are synchronized methods and synchronized statements?Synchronized methods are methods that are used to control access to an object. Athread only executes a synchronized method after it has acquired the lock for themethods object or class. Synchronized statements are similar to synchronizedmethods. A synchronized statement can only be executed after a thread hasacquired 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 datainto 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 aninstance of another class as an instance variable, and forward messages to theinstance. It is often safer than inheritance because it forces you to think about eachmessage you forward, because the instance is of a known class, rather than a newclass, and because it doesnt 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, itmakes you write more code, and it is harder to re-use (because it is not a subclass). © IT Engineering Portal : www.itportal.in 120
  • 121. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.INWhat does it mean that a method or field is "static"?Static variables and methods are instantiated only once per class. In other wordsthey are class variables, not instance variables. If you change the value of a staticvariable in a particular object, the value of that variable changes for all instances ofthat class.Static methods can be referenced with the name of the class rather than the nameof a particular object of the class (though that works too). Thats how librarymethods like System.out.println() work out is a static field in the java.lang.Systemclass.What is the difference between preemptive scheduling and time slicing?Under preemptive scheduling, the highest priority task executes until it enters thewaiting or dead states or a higher priority task comes into existence. Under timeslicing, a task executes for a predefined slice of time and then reenters the pool ofready tasks. The scheduler then determines which task should execute next, basedon 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 methodmust 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 ofthem 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 mostextensively used object. Strings in Java are instances of String class defined injava.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 destructorsthe way C++ does.Is exit a keyword in Java?No. To exit a program explicitly you use exit method in System object. © IT Engineering Portal : www.itportal.in 121
  • 122. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.INWhat happens if you dont initialize an instance variable of any of theprimitive types in Java?Java by default initializes it to the default value for that primitive type. Thus an intwill 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 aninstance variable?The object references are all initialized to null in Java. However in order to doanything useful with these references, you must set them to a valid object, else youwill get NullPointerException everywhere you try to use such default initializedreferences.What are the different scopes for Java variables?The scope of a Java variable is determined by the context in which the variable isdeclared. Thus a java variable can have one of the three scopes at any given pointin time.1. Instance : - These are typical object level variables, they are initialized to defaultvalues at the time of creation of object, and remain accessible as long as the objectaccessible.2. Local : - These are the variables that are defined within a method. They remainaccessible only during the course of method execution. When the method finishesexecution, these variables fall out of scope.3. Static: - These are the class level variables. They are initialized when the class isloaded in JVM for the first time and remain there as long as the class remainsloaded. 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 norobject references. If you try to use these variables without initializing themexplicitly, the java compiler will not compile the code. It will complain about thelocal 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 notinitialized.Can a public class MyClass be defined in a source file namedYourClass.java?No the source file name, if it contains a public class, must be the same as thepublic 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. © IT Engineering Portal : www.itportal.in 122
  • 123. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.INWhat 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 aninstance variable?If the array is an array of primitive types, then all the elements of the array will beinitialized to the default value corresponding to that primitive type. e.g. All theelements of an array of int will be initialized to 0, while that of Boolean type will beinitialized to false. Whereas if the array is an array of references (of any type), all theelements will be initialized to null.--------------------------------------------------------------- © IT Engineering Portal : www.itportal.in 123
  • 124. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.IN JDBC Interview Questions & Answers © IT Engineering Portal : www.itportal.in 124
  • 125. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.INJDBC Interview Questions and AnswersWhat is JDBC?JDBC may stand for Java Database Connectivity. It is also a trade mark. JDBC is a layerof abstraction that allows users to choose between databases. It allows you to change toa different database engine and to write to a single API. JDBC allows you to writedatabase applications in Java without having to concern yourself with the underlyingdetails of a particular database.Whats 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 Javaapplication and a relational database. The JDBC API is released in two versions; JDBCversion 1.22 (released with JDK 1.1.X in package java.sql) and version 2.0 (released withJava platform 2 in packages java.sql and javax.sql). It is a simple and powerful largelydatabase-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 asNetscape Navigator, isnt allowed. The JDBC-ODBC bridge doesnt allow untrusted codeto call it for security reasons. This is good because it means that an untrusted appletthat is downloaded by the browser cant circumvent Java security by calling ODBC.Remember that ODBC is native code, so once ODBC is called the Java programminglanguage cant guarantee that a security violation wont occur. On the other hand, PureJava JDBC drivers work well with applets. They are fully downloadable and do notrequire any client-side configuration.Finally, we would like to note that it is possible to use the JDBC-ODBC bridge withapplets that will be run in appletviewer since appletviewer assumes that applets aretrusted. In general, it is dangerous to turn applet security off, but it may be appropriatein certain controlled situations, such as for applets that will only be used in a secureintranet environment. Remember to exercise caution if you choose this option, and usean all-Java JDBC driver whenever possible to avoid security problems.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 JDBCtrace contains a detailed listing of the activity occurring in the system that is related toJDBC operations.If you use the DriverManager facility to establish your database connection, you use theDriverManager.setLogWriter method to enable tracing of JDBC operations. If you use aDataSource object to get a connection, you use the DataSource.setLogWriter method toenable tracing. (For pooled connections, you use theConnectionPoolDataSource.setLogWriter method, and for connections that canparticipate in distributed transactions, you use the XADataSource.setLogWriter method.) © IT Engineering Portal : www.itportal.in 125
  • 126. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.INWhat 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 languageinstead 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 theresultset.srs.afterLast();while (srs.previous()) {String name = srs.getString("COLUMN_1");float salary = srs.getFloat("COLUMN_2");//...c. to find a specific row, use absolute(), relative() methods.srs.absolute(4); // cursor is on the fourth rowint rowNum = srs.getRow(); // rowNum should be 4srs.relative(-3);int rowNum = srs.getRow(); // rowNum should be 1srs.relative(2);int rowNum = srs.getRow(); // rowNum should be 3d. 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 andthen, call updateRow() method.uprs.last();uprs.updateFloat("COLUMN_2", 25.55);//update last rows data © IT Engineering Portal : www.itportal.in 126
  • 127. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.INuprs.updateRow();//dont miss this method, otherwise,// the data will be lost.How can I use the JDBC API to access a desktop database like Microsoft Accessover the network?Most desktop databases currently require a JDBC solution that uses ODBC underneath.This is because the vendors of these database products havent implemented all-JavaJDBC drivers.The best approach is to use a commercial JDBC driver that supports ODBC and thedatabase you want to use. See the JDBC drivers page for a list of available JDBCdrivers.The JDBC-ODBC bridge from Suns Java Software does not provide network access todesktop databases by itself. The JDBC-ODBC bridge loads ODBC as a local DLL, andtypical ODBC drivers for desktop databases like Access arent networked. The JDBC-ODBC bridge can be used together with the RMI-JDBC bridge, however, to access adesktop 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 infunctionality between ODBC drivers, the functionality of the bridge may be affected. Thebridge 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 theDriverManager.getConnection method. The cause can be failing to load the appropriateJDBC drivers before calling the getConnection method, or it can be specifying an invalidJDBC URL--one that isnt recognized by your JDBC driver. Your best bet is to check thedocumentation for your JDBC driver or contact your JDBC driver vendor if you suspectthat 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 ormore the the shared libraries needed by the Bridge cannot be loaded. If you think this isthe cause, check your configuration to be sure that the shared libraries are accessible tothe Bridge.Why isnt the java.sql.DriverManager class being found?This problem can be caused by running a JDBC applet in a browser that supports theJDK 1.0.2, such as Netscape Navigator 3.0. The JDK 1.0.2 does not contain the JDBCAPI, so the DriverManager class typically isnt found by the Java virtual machine runningin the browser.Heres a solution that doesnt require any additional configuration of your web clients.Remember that classes in the java.* packages cannot be downloaded by most browsersfor security reasons. Because of this, many vendors of all-Java JDBC drivers supplyversions of the java.sql.* classes that have been renamed to jdbc.sql.*, along with aversion of their driver that uses these modified classes. If you import jdbc.sql.* in yourapplet code instead of java.sql.*, and add the jdbc.sql.* classes provided by your JDBCdriver vendor to your applets codebase, then all of the JDBC classes needed by theapplet can be downloaded by the browser at run time, including the DriverManager © IT Engineering Portal : www.itportal.in 127
  • 128. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.INclass.This solution will allow your applet to work in any client browser that supports the JDK1.0.2. Your applet will also work in browsers that support the JDK 1.1, although youmay want to switch to the JDK 1.1 classes for performance reasons. Also, keep in mindthat 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 insertuprs.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 5To see the changes call refreshRow();uprs.refreshRow();What are the two major components of JDBC?One implementation interface for database manufacturers, the other implementationinterface for application and applet writers.What is JDBC Driver interface?The JDBC Driver interface provides vendor-specific implementations of the abstractclasses provided by the JDBC API. Each vendor driver must provide implementations ofthe java.sql.Connection,Statement,PreparedStatement, CallableStatement, ResultSet andDriver.How do I retrieve a whole row of data at once, instead of calling an individualResultSet.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 © IT Engineering Portal : www.itportal.in 128
  • 129. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.INthat this is the cause of a performance problem, however, because it is difficult to seehow a column could be fetched without at least the cost of a function call in anyscenario. 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.driversRegister a driverSpecify a databaseOpen a database connectionSubmit a queryReceive resultsProcess resultsWhy does the ODBC driver manager return Data source name not found and nodefault driver specified Vendor: 0This 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 thatthe bridge-which is a normal ODBC client-has successfully called ODBC, so the problemisnt due to native libraries not being present. In this case, it appears that the error isdue to the fact that an ODBC DSN (data source name) needs to be configured on theclient machine. Developers often forget to do this, thinking that the bridge will magicallyfind the DSN they configured on their remote server machineHow to use JDBC to connect Microsoft Access?There is a specific tutorial at javacamp.org. Check it out.What are four types of JDBC driver?Type 1 DriversBridge drivers such as the jdbc-odbc bridge. They rely on an intermediary such as ODBCto transfer the SQL calls to the database and also often rely on native code. It is not aserious solution for an applicationType 2 DriversUse the existing database API to communicate with the database on the client. Fasterthan Type 1, but need native code and require additional permissions to work in anapplet. Client machine requires software to run.Type 3 DriversJDBC-Net pure Java driver. It translates JDBC calls to a DBMS-independent networkprotocol, which is then translated to a DBMS protocol by a server. Flexible. Pure Javaand no native code.Type 4 DriversNative-protocol pure Java driver. It converts JDBC calls directly into the networkprotocol used by DBMSs. This allows a direct call from the client machine to the DBMS © IT Engineering Portal : www.itportal.in 129
  • 130. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.INserver. It doesnt need any special native code on the client machine.Recommended by Suns tutorial, driver type 1 and 2 are interim solutions where directpure Java drivers are not yet available. Driver type 3 and 4 are the preferred way toaccess databases using the JDBC API, because they offer all the advantages of Javatechnology, including automatic installation. For more info, visit Sun JDBC pageWhich type of JDBC driver is the fastest one?JDBC Net pure Java driver(Type IV) is the fastest driver because it converts the jdbc callsinto vendor specific protocol calls and it directly interacts with the database.Are all the required JDBC drivers to establish connectivity to my database part ofthe JDK?No. There arent any JDBC technology-enabled drivers bundled with the JDK 1.1.x orJava 2 Platform releases other than the JDBC-ODBC Bridge. So, developers need to get adriver and install it before they can connect to a database. We are considering bundlingJDBC technology- enabled drivers in the future.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 itmakes to ODBC. Multi-threaded Java programs may use the Bridge, but they wont getthe advantages of multi-threading. In addition, deadlocks can occur between locks heldin the database and the semaphore used by the Bridge. We are thinking about removingthe synchronized methods in the future. They were added originally to make thingssimple for folks writing Java programs that use a single-threaded ODBC driver.Does the JDBC-ODBC Bridge support multiple concurrent open statements perconnection?No. You can open only one Statement object per connection when you are using theJDBC-ODBC Bridge.What is the query used to display all tables names in SQL Server (Queryanalyzer)?select * from information_schema.tablesWhy cant I invoke the ResultSet methods afterLast and beforeFirst when themethod next works?You are probably using a driver implemented for the JDBC 1.0 API. You need to upgradeto a JDBC 2.0 driver that implements scrollable result sets. Also be sure that your codehas 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 objecteach 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 retrievedata like strings using the JDBC API without always allocating a new object. © IT Engineering Portal : www.itportal.in 130
  • 131. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.INWe are studying this issue to see if it is an area in which the JDBC API should beimproved. 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 DriversType 1: JDBC-ODBC Bridge DriverType 2: Native API Partly Java DriverType 3: Network protocol DriverType 4: JDBC Net pure Java DriverWhat 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 andresponse change hands, the slower it will be. This means that Type 1 and Type 3 driverswill be slower than Type 2 drivers (the database calls are make at least three translationsversus 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 tofind 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. Ifthe result is not scrollable, you can either count the rows by iterating through the resultset or get the number of rows by submitting a query with a COUNT column in theSELECT clause.I would like to download the JDBC-ODBC Bridge for the Java 2 SDK, StandardEdition (formerly JDK 1.2). Im a beginner with the JDBC API, and I would like tostart with the Bridge. How do I do it?The JDBC-ODBC Bridge is bundled with the Java 2 SDK, Standard Edition, so there isno 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 JDBCtechnology-enabled driver, type 3 or 4, in order to get all of the benefits of the Javaprogramming language and the JDBC API.Once I have the Java 2 SDK, Standard Edition, from Sun, what else do I need toconnect to a database?You still need to get and install a JDBC technology-enabled driver that supports thedatabase 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 upalready. The Bridge comes with the Java 2 SDK, Standard Edition, and Enterprise © IT Engineering Portal : www.itportal.in 131
  • 132. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.INEdition, and it doesnt require any extra setup itself. The Bridge is a normal ODBC client.Note, however, that you should use the JDBC-ODBC Bridge only for experimentalprototyping or when you have no other driver available.What is the best way to generate a universally unique object ID? Do I need touse 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 theSystem.currentTimeMillis() call.2: Unique across a cluster. Digits 9-16 are the encoded representation of the 32 bitinteger of the underlying IP address.3: Unique down to the object in a JVM. Digits 17-24 are the hex representation of the callto System.identityHashCode(), which is guaranteed to return distinct integers for distinctobjects within a JVM.4: Unique within an object within a millisecond. Finally digits 25-32 represent a random32 bit integer generated on every method call using the cryptographically strongjava.security.SecureRandom class.Answer1There 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 beopening up a potential security issue. This is why ProcessIDs are randomized on someOSes (AIX for one). 2. You must synchronize on that counter to guarantee that yournumber isnt reused. Your random number generator need not be synchronized, (thoughits implementation may be).Answer21) If your using Oracle You can create a sequence ,by which you can generate uniqueprimary key or universal primary key. 2) you can generate by using random numbers butyou may have to check the range and check for unique id. ie random number generate0.0 to 1.0 u may have to make some logic which suits your unique id 3) Set themaximum value into an XML file and read that file at the time of loading your applicationfrom xml .What happens when I close a Connection application obtained from a connectionPool? How does a connection pool maintain the Connections that I had closedthrough the application?Answer1It is the magic of polymorphism, and of Java interface vs. implementation types. Twoobjects can both be "instanceof" the same interface type, even though they are not of thesame 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 youdirectly 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 poolcache manager. © IT Engineering Portal : www.itportal.in 132
  • 133. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.INThe close() method of the "logical" connection object, while it satisfies the methodsignature of close() in the java.sql.Connection interface, does not actually close theunderlying physical connection.Answer2Typically a connection pool keeps the active/in-use connections in a hashtable or otherCollection mechanism. Ive seen some that use one stack for ready-for-use, one stack forin-use.When close() is called, whatever the mechanism for indicating inuse/ready-for-use, thatconnection 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 areclosing where the minimum are already available should be physically closed.Some connection pools periodically test their connections to see if queries work on theready-for-use connections or they may test that on the close() method before returning tothe ready-for-use pool.How do I insert a .jpg into a mySQL data base? I have tried inserting the file asbyte[], but I recieve an error message stating that the syntax is incorrect.Binary data is stored and retrieved from the database usingstreams 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 convertsit 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); © IT Engineering Portal : www.itportal.in 133
  • 134. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.IN}/*** 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 {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_tabwhere 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);int n=in.read(b); © IT Engineering Portal : www.itportal.in 134
  • 135. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.INSystem.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.*/public static void main(String[] args) {String fileName="c:tmpf128.jpg";StoreBinary sb = new StoreBinary();try {if (sb.storeImageFile(fileName)) {// stored ok, now get it back againImage img=sb.getImageFile(fileName);}}catch (Exception ex) { © IT Engineering Portal : www.itportal.in 135
  • 136. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.INex.printStackTrace();}}}How can I know when I reach the last record in a table, since JDBC doesntprovide an EOF method?Answer1You 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 reachedthe end of the current ResultSet, not necessarily the end of the table. SQL and RDBMSesmake no guarantees about the order of rows, even from sequential SELECTs, unless youspecifically use ORDER BY. Even then, that doesnt necessarily tell you the order of datain the table.Answer2Assuming you mean ResultSet instead of Table, the usual idiom for iterating over aforward 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 JDBCdriver?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 SourceJDBC 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 RowSetpackage is the most commonly available and offers thesun.jdbc.rowset.RowSetMetaDataImpl class. After instantiation, any of theRowSetMetaData setter methods may be used. The bare minimum needed for a RowSetto function is to set the Column Count for a row and the Column Types for each columnin 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 usingCachedRowSet.setReader(javax.sql.RowSetReader reader). Once that is done, a call toCachedRowSet.execute() will, among other things, invoke the readData method.How do I implement a RowSetReader? I want to populate a CachedRowSetmyself and the documents specify that a RowSetReader should be used. Thesingle method accepts a RowSetInternal caller and returns void. What can I do © IT Engineering Portal : www.itportal.in 136
  • 137. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.INin the readData method?"It can be implemented in a wide variety of ways..." and is pretty vague about what canactually 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 meaninserting rows, so the code would move to the insert row, set the column data and insertrows. Then the cursor must be set to to the appropriate position.How can I instantiate and load a new CachedRowSet object from a non-JDBCsource?The basics are:* Create an object that implements javax.sql.RowSetReader, which loads the data.* Instantiate a CachedRowset object.* Set the CachedRowsets reader to the reader object previously created.* Invoke CachedRowset.execute().Note that a RowSetMetaData object must be created, set up with a description of thedata, and attached to the CachedRowset before loading the actual data.The following code works with the Early Access JDBC RowSet download available fromthe Java Developer Connection and is an expansion of one of the examples:// Independent data source CachedRowSet Exampleimport 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 readerSystem.out.println("Fetching from RowSet...");while(crs.next()){showTheData(); © IT Engineering Portal : www.itportal.in 137
  • 138. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.IN} // end while nextif(crs.isAfterLast() == true){System.out.println("We have reached the end");System.out.println("crs row: " +crs.getRow());}System.out.println("And now backwards...");while(crs.previous()){showTheData();} // end while previousif(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 arent before the first row."); }crs.last();if(crs.isLast() == true){ System.out.println("...and now we have moved to the last");}System.out.println("crs row: " +crs.getRow());if(crs.isAfterLast() == false){ © IT Engineering Portal : www.itportal.in 138
  • 139. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.INSystem.out.println("we arent after the last.");}} // end trycatch (SQLException ex){System.err.println("SQLException: " +ex.getMessage());}} // end constructorpublic 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" );}else{ System.out.println("sCol3 is nulln"); }} // end showTheData// RowSetReader implementationpublic void readData(RowSetInternal caller)throws SQLException{rsmdi = new RowSetMetaDataImpl();rsmdi.setColumnCount(3);rsmdi.setColumnType(1, Types.VARCHAR); © IT Engineering Portal : www.itportal.in 139
  • 140. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.INrsmdi.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 readDatapublic static void main(String args[]){new RowSetEx1();}} // end class RowSetEx1Can I set up a connection pool with multiple user IDs? The single ID we areforced to use causes problems when debugging the DBMS.Since the Connection interface ( and the underlying DBMS ) requires a specific user andpassword, theres not much of a way around this in a pool. While you could create adifferent 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 logexecuted 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 andtimestamp as standard columns in your tables. In this last case, you would collect aseparate user value in your program.How can I protect my database password ? Im writing a client-side javaapplication that will access a database over the internet. I have concerns aboutthe security of the database passwords. The client will have access in one way oranother to the class files, where the connection string to the database, includinguser and password, is stored in as plain text. What can I do to protect my © IT Engineering Portal : www.itportal.in 140
  • 141. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.INpasswords?This is a very common question.Conclusion: JAD decompiles things easily and obfuscation would not help you. But youdhave the same problem with C/C++ because the connect string would still be visible inthe executable.SSL JDBC network drivers fix the password sniffing problem (in MySQL 4.0), but not thedecompile problem. If you have a servlet container on the web server, I would go thatroute (see other discussion above) then you could at least keep people fromreading/destroying your mysql database.Make sure you use database security to limit that app user to the minimum tables thatthey 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 toembed user ID and password into program code. One could generally see the text evenwithout 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 toenter the information or keep it in a properties file.Detecting Duplicate Keys I have a program that inserts rows in a table. My tablehas a column Name that has a unique constraint. If the user attempts to inserta duplicate name into the table, I want to display an error message byprocessing the error code from the database. How can I capture this error codein a Java program?A solution that is perfectly portable to all databases, is to execute a query for checking ifthat unique value is present before inserting the row. The big advantage is that you canhandle your error message in a very simple way, and the obvious downside is that youare going to use more time for inserting the record, but since youre working on a PKfield, performance should not be so bad.You can also get this information in a portable way, and potentially avoid anotherdatabase access, by capturing SQLState messages. Some databases get more specificthan others, but the general code portion is 23 - "Constraint Violations". UDB2, forexample, 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 synchronizationbottlenecks.Can you scroll a result set returned from a stored procedure? I am returning aresult set from a stored procedure with type SQLRPGLE but once I reach the endof the result set it does not allow repositioning. Is it possible to scroll this resultset?A CallableStatement is no different than other Statements in regard to whether relatedResultSets are scrollable. You should create the CallableStatement usingConnection.prepareCall(String sql, int resultSetType, int resultSetConcurrency). © IT Engineering Portal : www.itportal.in 141
  • 142. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.INHow 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-1characters and those above 255 ( hex FF ). The reason for that is that all Java charactersare in Unicode ( unless you perform/request special encoding ). Implicit in thatstatement is the presumption that the data store can handle characters outside the hexFF range or interprets different character sets appropriately. That means either:* The OS, application and database use the same code page and character set. Forexample, 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 supportvaries. Particular DBMSes may allow setting the encoding/code page/CCSID at thedatabase, table or even column level. There is no particular standard for providedsupport or methods of setting the encoding. You have to check the DBMS documentationand set up the table properly.* The DBMS has I18N support in the form of Unicode capability. This would handle anyUnicode 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 withexclusive mode. Depending on your database engine, you can lock tables or rows inexclusive mode.In Oracle you would create a statement st and runst.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, soyoull have to change it depending on your database. But they can all be done withexecute().What are the standard isolation levels defined by JDBC?The values are defined in the class java.sql.Connection and are:* TRANSACTION_NONE © IT Engineering Portal : www.itportal.in 142
  • 143. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.IN* TRANSACTION_READ_COMMITTED* TRANSACTION_READ_UNCOMMITTED* TRANSACTION_REPEATABLE_READ* TRANSACTION_SERIALIZABLEUpdate fails without blank padding. Although a particular row is present in thedatabase 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 with14 spaces), the update then works!!! Is there any solution to this problemwithout 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, includingsize and trailing blanks. As Alessandro indicates, defining CHAR columns to beVARCHAR is the most general answer.What isolation level is used by the DBMS when inserting, updating and selectingrows from a database?The answer depends on both your code and the DBMS. If the program does not explicitlyset the isolation level, the DBMS default is used. You can determine the default usingDatabaseMetaData.getDefaultTransactionIsolation() and the level for the currentConnection with Connection.getTransactionIsolation(). If the default is not appropriatefor 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 remotedatabase 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 tohave a local class behind the proxy connect to the database for you, then you need aservlet/JSP to receive an HTTP request and use the local class to connect to the databaseand send the response back to the client.You could also use RMI where your remote computer class that connects to the databaseacts as a remote server that talks RMI with the clients. if you implement this, then youwill need to tunnel RMI through HTTP which is not that hard.In summary, either have a servlet/JSP take HTTP requests, instantiate a class thathandles database connections and send HTTP response back to the client or have thelocal 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 adiscussion of standard JDBC syntax for dealing with result, IN, IN/OUT and OUTparameters, see Stored Procedures. © IT Engineering Portal : www.itportal.in 143
  • 144. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.INHow 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 tothe current log.How can I get or redirect the log used by DriverManager and JDBC drivers?As of JDBC 2.0, use DriverManager.getLogWriter() andDriverManager.setLogWriter(PrintWriter out). Prior to JDBC 2.0, the DriverManagermethods getLogStream() and setLogStream(PrintStream out) were used. These are nowdeprecated.What does it mean to "materialize" data?This term generally refers to Array, Blob and Clob data which is referred to in thedatabase via SQL locators "Materializing" the data means to return the actual datapointed 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 typeSome rationales for using Locators rather than directly returning the data can be seenmost clearly with the Blob type. By definition, a Blob is an arbitrary set of binary data. Itcould be anything; the DBMS has no knowledge of what the data represents. Notice thatthis effectively demolishes data independence, because applications must now be awareof what the Blob data actually represents. Lets assume an employee table that includesemployee images as Blobs.Say we have an inquiry program that presents multiple employees with department andidentification information. To see all of the data for a specific employee, including theimage, the summary row is selected and another screen appears. It is only at this pontthat the application needs the specific image. It would be very wasteful and timeconsuming to bring down an entire employee page of images when only a few would everbe selected in a given run.Now assume a general interactive SQL application. A query is issued against theemployee table. Because the image is a Blob, the application has no idea what to do withthe data, so why bring it down, killing performance along the way, in a long runningoperation?Clearly this is not helpful in those applications that need the data everytime, but theseand 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 adatabase server. Read "logical pointer" here as an identifier the DBMS can use to locateand 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 typicallyuse Locators under the covers to handle Array, Blob, and Clob data types. © IT Engineering Portal : www.itportal.in 144
  • 145. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.INHow 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 forthe specific driver. There is no standard, other than user and password, for what theseproperties should be. Therefore, the developer is dependent on the driver documentationto automatically pass properties. For a standard dynamic method that can be used tosolicit user input for properties, see What properties should I supply to a database driverin order to connect to a database?In addition, a driver may specify its own method of accepting properties. Many do this viaappending the property to the JDBC Database URL. However, a JDBC Compliant drivershould implement the connect(String url, Properties info) method. This is generallyinvoked through DriverManager.getConnection(String url, Properties info).The passed properties are ( probably ) stored in variables in the Driver instance. This,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 thedeveloper and normally should be preferred over a standard Statement.Otherwise, the JDBC syntax is really the same as SQL syntax. One problem that oftenaffects newbies ( and others ) is that SQL, like many languages, requires quotes aroundcharacter ( read "String" for Java ) values to distinguish from numerics. So the clause:"WHERE myCol = " + myValis perfectly valid and works for numerics, but will fail when myVal is a String. Insteaduse:"WHERE myCol = " + myVal + ""if myVal equals "stringValue", the clause works out to:WHERE myCol = stringValueYou 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 connectionshave been reached?Use DatabaseMetaData.getMaxConnections() and compare to the number of connectionscurrently open. Note that a return value of zero can mean unlimited or, unfortunately,unknown. Of course, driverManager.getConnection() will throw an exception if aConnection 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 itstime 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 somesort of client install. Along with the install, various environment variables and path orclasspath settings must be in place. Because the requirements and installationprocedures vary with the provider, there is no reasonable way to provide details here. Atype 4 driver, on the other hand, is pure Java and should never exhibit this problem. Thetrade off is that a type 4 driver is usually slower. © IT Engineering Portal : www.itportal.in 145
  • 146. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.INMany connections from an Oracle8i pooled connection returns statement closed.I am using import oracle.jdbc.pool.* with thin driver. If I test with manysimultaneous connections, I get an SQLException that the statement is closed.ere is an example of concurrent operation of pooled connections from theOracleConnectionPoolDataSource. There is an executable for kicking off threads, aDataSource, and the workerThread.The Executable Memberpackage 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();}while ( i++ < 10 ) {try{workerClass worker = new workerClass();worker.setThreadNumber( i );worker.setConnectionPoolDataSource( dataSource.getConnectionPoolDataSource() );worker.start();System.out.println( "Started Thread#"+i ); © IT Engineering Portal : www.itportal.in 146
  • 147. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.IN}catch ( Exception ex ){ex.printStackTrace();}}}}The DataSource Memberpackage 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 instanceocpds = new OracleConnectionPoolDataSource();// Set connection parametersocpds.setURL("jdbc:oracle:oci8:@mydb");ocpds.setUser("scott");ocpds.setPassword("tiger");}public OracleConnectionPoolDataSourcegetConnectionPoolDataSource() {return ocpds;}}The Worker Thread Memberpackage package6;import oracle.jdbc.pool.*; © IT Engineering Portal : www.itportal.in 147
  • 148. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.INimport 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*/public workerClass() {}public void doWork( ) throws SQLException {// Create a pooled connectionpc = ocpds.getPooledConnection();// Get a Logical connectionconn = pc.getConnection();// Create a StatementStatement stmt = conn.createStatement ();// Select the ENAME column from the EMP tableResultSet rset = stmt.executeQuery ("select ename from emp");// Iterate through the result and print the employee nameswhile (rset.next ())// System.out.println (rset.getString (1));;// Close the RseultSetrset.close();rset = null;// Close the Statementstmt.close();stmt = null; © IT Engineering Portal : www.itportal.in 148
  • 149. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.IN// Close the logical connectionconn.close();conn = null;// Close the pooled connectionpc.close();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 ProducedStarted Thread#1Started Thread#2Started Thread#3Started Thread#4Started Thread#5Started Thread#6Started Thread#7Started Thread#8Started Thread#9Started Thread#10workerClass.thread# 1 completed.. © IT Engineering Portal : www.itportal.in 149
  • 150. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.INworkerClass.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 theoracle.jdbc.pool.OracleDataSource which should also be looked over, that is what youreally what to use. Here is a similar example that uses theoracle.jdbc.pool.OracleConnectionCacheImpl. The general construct is the same as thefirst example but note the differences in workerClass1 where some statements have beencommented ( basically a clone of workerClass from previous example ).The Executable Memberpackage package6;import java.sql.*;import javax.sql.*;import oracle.jdbc.pool.*;/*** package6.executableTester2**/public class executableTester2 {static int i = 0;protected static myOracleConnectCacheconnectionCache = null;/*** Constructor*/public executableTester2() throws SQLException{}/*** main* @param args*/public static void main(String[] args) {OracleConnectionPoolDataSource dataSource = null;try{ © IT Engineering Portal : www.itportal.in 150
  • 151. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.INdataSource = 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{connectionCache.close();} catch ( SQLException x) {x.printStackTrace();}this.finalize();}}The ConnectCacheImpl Memberpackage 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 © IT Engineering Portal : www.itportal.in 151
  • 152. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.INOracleConnectionCacheImpl {/*** Constructor*/public myOracleConnectCache( ConnectionPoolDataSource x)throws SQLException {initialize();}public void initialize() throws SQLException {setURL("jdbc:oracle:oci8:@myDB");setUser("scott");setPassword("tiger");//// 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 Memberpackage package6;import oracle.jdbc.pool.*;import java.sql.*;import javax.sql.*;/*** package6.workerClass1**/public class workerClass1 extends Thread {// protected OracleConnectionPoolDataSourceocpds = null;// protected PooledConnection pc = null;protected Connection conn = null;protected int threadNumber = 0;/** © IT Engineering Portal : www.itportal.in 152
  • 153. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.IN* Constructor*/public workerClass1() {}public void doWork( ) throws SQLException {// Create a pooled connection// pc = ocpds.getPooledConnection();// Get a Logical connection// conn = pc.getConnection();// Create a StatementStatement stmt = conn.createStatement ();// Select the ENAME column from the EMP tableResultSet rset = stmt.executeQuery("select ename from EMP");// Iterate through the result// and print the employee nameswhile (rset.next ())// System.out.println (rset.getString (1));;// Close the RseultSetrset.close();rset = null;// Close the Statementstmt.close();stmt = null;// Close the logical connectionconn.close();conn = null;// Close the pooled connection// pc.close();// pc = null;System.out.println( "workerClass1.thread#"+threadNumber+" completed..");} © IT Engineering Portal : www.itportal.in 153
  • 154. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.INpublic 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 ProducedStarted Thread#1Started Thread#2workerClass1.thread# 1 completed..workerClass1.thread# 2 completed..Started Thread#3Started Thread#4Started Thread#5workerClass1.thread# 5 completed..workerClass1.thread# 4 completed..workerClass1.thread# 3 completed..Started Thread#6Started Thread#7Started Thread#8Started Thread#9workerClass1.thread# 8 completed..workerClass1.thread# 9 completed..workerClass1.thread# 6 completed..workerClass1.thread# 7 completed..Started Thread#10workerClass1.thread# 10 completed.. DB2 Universal claims to support JDBC 2.0, But © IT Engineering Portal : www.itportal.in 154
  • 155. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.INI 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 the2.0 driver and JDK support. For detailed information, see Setting the Environment inBuilding Java Applets and Applications. The page includes instructions for mostsupported 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 wont allow the constraint to be applied after table creation.Most databases allow a default value for the column as well. The following SQL statementdisplays 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 fields value with ResultSet.getxxx when it is a NULL? I have triedto execute a typical SQL statement:select * from T-name where (clause);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 andany chained exceptions to determine if another problem exists. In general, one mayretrieve one of three values for a column that is null, depending on the data type. Formethods that return objects, null will be returned; for numeric ( get Byte(), getShort(),getInt(), getLong(), getFloat(), and getDouble() ) zero will be returned; for getBoolean() falsewill 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 SQLExceptionpublic void setNull(int paramIndex, int sqlType, String typeName) throws SQLExceptionThese methods assume that the columns are nullable. In this case, you can also justomit the columns in an INSERT statement; they will be automatically assigned nullvalues.Is there a way to find the primary key(s) for an Access Database table? SunsJDBC-ODBC driver does not implement the getPrimaryKeys() method for theDatabaseMetaData Objects.// Use meta.getIndexInfo() will//get you the PK index. Once// you know the index, retrieve its column nameDatabaseMetaData meta = con.getMetaData(); © IT Engineering Portal : www.itportal.in 155
  • 156. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.INString key_colname = null;// get the primary key informationrset = meta.getIndexInfo(null,null, table_name, true,true);while( rset.next()){String idx = rset.getString(6);if( idx != null){//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 cant 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 DBfrom JSP.javax.servlet.ServletException : oracle.jdbc.driver.OracleDriverjava.lang.ClassNotFoundException: oracle:jdbc:driver:OracleDriverBut, 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%libdirectory 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 aJTable. 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?Is there another way of dealing with the result set that could execute faster? © IT Engineering Portal : www.itportal.in 156
  • 157. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.INjava.util.Vector is largely thread safe, which means that there is a greater overhead incalling addElement() as it is a synchronized method. If your result set is very large, andthreading is not an issue, you could use one of the thread-unsafe collections in Java 2 tosave 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, whichwill obviously cause a large overhead - instead, use an AbstractTableModel and providean implementation which only loads data on demand, i.e. when (if) the user scrolls downthrough 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 atransaction is often described as a Logical Unit of Work ( LUW ). The rationale fortransactions is that you want to know definitively that all or none of the LUW completedsuccessfully. Note that this automatically gives you restart capability. Typically, there aretwo conditions under which you would want to use transactions:* Multiple statements involving a single file - An example would be inserting all of agroup of rows or all price updates for a given date. You want all of these to take effect atthe same time; inserting or changing some subset is not acceptable.* Multiple statements involving multiple files - The classic example is transferring moneyfrom one account to another or double entry accounting; you dont want the debit tosucceed and the credit to fail because money or important records will be lost. Anotherexample 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 completedsuccessfully, you A) want to know that the transaction was unsuccessful and B) that aportion of the transaction was not lost or dangling.Therefore, determining what completes the transaction or LUW should be the decidingfactor 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 thatreturned by DatabaseMetaData.getImportedKeys(), except that the information relates toother tables that reference the given table as a foreign key container. © IT Engineering Portal : www.itportal.in 157
  • 158. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.INHow can I get information about foreign keys used in a table?DatabaseMetaData.getImportedKeys() returns a ResultSet with data about foreign keycolumns, 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 JDBCAPI deals with this problem is to allow any query string to be passed through to anunderlying DBMS driver. This means that an application is free to use as much SQLfunctionality as desired, but it runs the risk of receiving an error on some DBMSs. Infact, an application query may be something other than SQL, or it may be a specializedderivative of SQL designed for specific DBMSs (for document or image queries, forexample)."Clearly this means either giving up portability or checking the DBMS currently usedbefore invoking specific operations.What is DML?DML is an abbreviation for Data Manipulation Language. This portion of the SQLstandard is concerned with manipulating the data in a database as opposed to thestructure of a database. The core verbs for DML are SELECT, INSERT, DELETE,UPDATE, COMMIT and ROLLBACK.What is the significance of DataBaseMetaData.tableIndexStatistics? How toobtain and use it?To answer the second question first, the tableIndexStatistic constant in the TYPE columnwill identify one of the rows in the ResultSet returned whenDatabaseMetaData.getIndexInfo() is invoked. If you analyze the wordy API, atableIndexStatistic row will contain the number of rows in the table in the CARDINALITYcolumn 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 thepool.* Distributed - Provides a Connection that can participate in distributed transactions (more than one DBMS is involved). It is anticipated, but not enforced, that a distributedDataSource will also provide pooling.However, there are no standard methods available in the DataSource class to determineif 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 isdefined to the DataSource outside the application ( Of course, a production quality appcan and should provide this information outside the app anyway, usually with propertiesfiles or ResourceBundles ). The documentation expresses the view that DataSource willreplace the common DriverManager method. © IT Engineering Portal : www.itportal.in 158
  • 159. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.INDoes the database server have to be running Java or have Java support in orderfor my remote JDBC client app to access the database?The answer should always be no. The two critical requirements are LAN/internetconnectivity and an appropriate JDBC driver. Connectivity is usually via TCP/IP, butother communication protocols are possible. Unspoken, but assumed here is that theDBMS has been started to listen on a communications port. It is the JDBC drivers job toconvert the SQL statements and JDBC calls to the DBMS native protocol. From theservers point of view, its just another data request coming into the port, theprogramming 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 alwaysadhere to standards as closely as we would like, including differing names for standardJava types. To deal with this, first, there are a number of tables available in the JDKJDBC documentation dealing with types.Are the code examples from the JDBC API Tutorial and Reference, Second Editionavailable online?Yes.When an SQL select statement doesnt return any rows, is an SQLExceptionthrown?No. If you want to throw an exception, you could wrap your SQL related code in a customclass and throw something like ObjectNotFoundException when the returned ResultSetis empty.Why should I consider optimistic versus pessimistic approaches to databaseupdates?In a modern database, possibly the two most important issues are data integrity andconcurrency ( multiple users have access to and can update the data ). Either approachcan be appropriate, depending on the application, but it is important to be aware ofpossible consequences to avoid being blindsided.A pessimistic approach, with locks, is usually seen as good for data integrity, although itcan be bad for concurrency, especially the longer a lock is held. In particular, itguarantees against lost updates - defined as an update performed by one processbetween the time of access and update by another process, which overwrites the interimupdate. However, other users are blocked from updating the data and possibly reading itas well if the read access also tries to acquire a lock. A notorious problem can arise whena user accesses data for update and then doesnt act on it for a period of time. Anothersituation that occurred with one of my clients is that a batch ( non-interactive ) processmay 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 iswritten, more problems may be introduced. ( No, we did not write the interactive updateprogram and yes, we had recovery procedures in place. )An optimstic approach can alleviate lock concurrency problems, but requires more codeand care for integrity. The "optimistic" definition usually says that expectations of updateclashes are rare, but I view them as normal occurrances in a heavily used database. The © IT Engineering Portal : www.itportal.in 159
  • 160. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.INbasics are that any changes between time of access and time of update must be detectedand taken into account. This is often done by comparing timestamps, but one must besure that the timestamp is always changed for an update and, of course, that the tablecontains a timestamp column. A more involved, but more complete method involvessaving the original columns and using them in the Where clause of the Updatestatement. If the update fails, the data has changed and the latest data should bereaccessed.What is optimistic concurrency?An optimistic approach dispenses with locks ( except during the actual update ) andusually involves comparison of timestamps, or generations of data to ensure that datahasnt changed between access and update times. Its generally explained that the termoptimistic is used because the expectation is that a clash between multiple updates tothe same data will seldom occur.What is pessimistic concurrency?With a pessimistic approach, locks are used to ensure that no users, other than the onewho holds the lock, can update data. Its generally explained that the term pessimistic isused because the expectation is that many users will try to update the same data, so oneis 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. Somevendors also implement Select... for Update, which explicitly acquires a lock.Can I get information about a ResultSets associated Statement and Connectionin a method without having or adding specific arguments for the Statement andConnection?Yes. Use ResultSet.getStatement(). From the resulting Statement you can useStatement.getConnection().How can I tell if my JDBC driver normalizes java.sql.Date and java.sql.Timeobjects?To actually determine the values, the objects must be converted to a java.util.Date andexamined. See What does normalization mean for java.sql.Date and java.sql.Time? for thedefinition of normalization. Notice that even a debugger will not show whether theseobjects have been normalized, since the getXXX methods in java.sql.Date for timeelements and in java.sql.Time for date elements throw an exception.So, while a java.sql.Date may show 2001-07-26, its normalized only if the java.util.Datevalue is:Thu Jul 26 00:00:00 EDT 2001and while a java.sql.Time may show 14:01:00, its normalized only if the java.util.Datevalue is:Thu Jan 01 14:01:00 EST 1970What is the most efficient method of replicating data between databases usingJDBC?Within Java, the most efficient method would be, opening connections using the JDBCand inserting or updating the records from one database to the other database, but it © IT Engineering Portal : www.itportal.in 160
  • 161. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.INdepends upon the databases being replicated. If you are using Oracle databases, it hasstandard methods for replication, and you do not need the JDBC for the replication. Usesnapshots like updateable and read-only.There are different kind of replication. Let us consider the most widely used ones:A) One Master - One slaveI) If there is not a significant difference between the structure of the database tables, thefollowing method would be useful.FromDatabase=A; ToDatabase=B1) 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 differentqueries.II)If there is significant difference between the structure of the database tables, thefollowing method would be useful.FromDatabase=A; ToDatabase=B1) 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 thedatabase 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 tothe different entities in the XML file.6) Transform the XMLA file using the XSL and XSLT to the format useful for the databaseB 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.B) One Master - Multiple slavesThe difference here is to open multiple JDBC connections to write to the differentdatabases one record at a time.C) Multiple Masters:For multiple masters, use timestamps to compare the times of the records to find outwhich 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 thisscenario.What is the difference between setMaxRows(int) and SetFetchSize(int)? Caneither reduce processing time?setFetchSize(int) defines the number of rows that will be read from the database when © IT Engineering Portal : www.itportal.in 161
  • 162. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.INthe ResultSet needs more rows. The method in the java.sql.Statement interface will setthe default value for all the ResultSet derived from that Statement; the method in thejava.sql.ResultSet interface will override that value for a specific ResultSet. Sincedatabase fetches can be expensive in a networked environment, fetch size has an impacton performance.setMaxRows(int) sets the limit of the maximum nuber of rows in a ResultSet object. Ifthis limit is exceeded, the excess rows are "silently dropped". Thats all the API says, sothe setMaxRows method may not help performance at all other than to decrease memoryusage. A value of 0 (default) means no limit.Since were talking about interfaces, be careful because the implementation of drivers isoften different from database to database and, in some cases, may not be implemented orhave 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 dont create anothertable. How can I resolve the issue?While the questioner found a partially workable method for his particular DBMS, asmentioned in the section on transactions in my JDBC 2.0 Fundamentals Short Course:DDL statements in a transaction may be ignored or may cause a commit to occur. Thebehavior is DBMS dependent and can be discovered by use ofDatabaseMetaData.dataDefinitionCausesTransactionCommit() andDatabaseMetaData.dataDefinitionIgnoredInTransactions(). One way to avoid unexpectedresults is to separate DML and DDL transactions.The only generally effective way to "rollback" table creation is to delete the table.Whats the best way, in terms of performance, to do multiple insert/updatestatements, a PreparedStatement or Batch Updates?Because PreparedStatement objects are precompiled, their execution can be faster thanthat of Statement objects. Consequently, an SQL statement that is executed many timesis often created as a PreparedStatement object to increase efficiency.A CallableStatement object provides a way to call stored procedures in a standardmanner for all DBMSes. Their execution can be faster than that of PreparedStatementobject.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 towhether 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 columnheaders. Any ideas?One possibility: Have an optional field in your form or GET url called (appropriately) © IT Engineering Portal : www.itportal.in 162
  • 163. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.INORDER with a default value of either "no order" or whatever you want your defaultordering to be (i.e. timestamp, username, whatever). When you get your request, seewhat the value of the ORDER element is. If its null or blank, use the default. Use thatvalue to build your SQL query, and display the results to the page. If youre caching datain your servlet, you can use the Collection framework to sort your data (seejava.util.Collections) if you can get it into a List format. Then, you can create a Collatorwhich can impose a total ordering on your results.What are the components of the JDBC URL for Oracles "thin" driver and how doI use them?Briefly: jdbc:oracle:thin:@hostname:port:oracle-sid1. 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 communicate withserver.2. in red the network machine name, or its ip address, to locate the server where oracleis 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:MyDBIHeres an example:jdbc:oracle:thin:scott/tiger@MyOracleHost:1521:MyDBwhere user=scott and pass=tiger.Why doesnt 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 aretreated as strings. In Java 1.4, these URL strings have a class called java.net.URI.However, you still cant 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 allowsretrieval. Keep in mind that prior ResultSet warnings are cleared on each new read andprior Statement warnings are cleared with each new execution. getWarnings() itself doesnot clear existing warnings, but each object has a clearWarnings method.Whats the fastest way to normalize a Time object?Of the two recommended ways when using a Calendar( see How do I create ajava.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() ); © IT Engineering Portal : www.itportal.in 163
  • 164. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.INwas always at least twice as fast as: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 timedifference 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 timecomponents. java.sql.Date should carry only date information and a normalized instancehas the time information set to zeros. java.sql.Time should carry only time informationand a normalized instance has the date set to the Java epoch ( January 1, 1970 ) and themilliseconds 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 dayvalues. 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, secondand millisecond values must be set to zero. At that point, Calendar.getTime().getTime() isinvoked to get the java.util.Date milliseconds. That value is then passed to ajava.sql.Date constructor:Calendar cal = Calendar.getInstance();// set Date portion to January 1, 1970cal.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() );The second method is java.sql.Dates valueOf method. valueOf() accepts a String, whichmust 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 aCalendar object, use:java.sql.Date jsqlD = java.sql.Date.valueOf( © IT Engineering Portal : www.itportal.in 164
  • 165. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.INcal.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 secondvalues. 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 Javas 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 thenpassed to a Time constructor:Calendar cal = Calendar.getInstance();// set Date portion to January 1, 1970cal.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 Times valueOf method. valueOf() accepts a String, which must bethe 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 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 scalarvalues. For a list of those supported and additional information, see section A.1.4Support Scalar Functions in the JDBC Data Access API For Driver Writers. Note thatdrivers are only expected to support those scalar functions that are supported by theunderlying DB engine.What does setFetchSize() really do?The API documentation explains it pretty well, but a number of programmers seem tohave a misconception of its functionality. The first thing to note is that it may do nothingat all; it is only a hint, even to a JDBC Compliant driver. setFetchSize() is really a request © IT Engineering Portal : www.itportal.in 165
  • 166. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.INfor 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 moreefficient. It may be more efficient on the server side as well, depending on the particularSQL statement and the DB engine. That would be true if the data could be read straightoff an index and the DB engine paid attention to the fetch size. In that case, the DBengine could return only enough data per request to match the fetch size. Dont count onthat behavior. In general, the fetch size will be transparent to your program and onlydetermines how often requests are sent to the server as you traverse the data.Also, both Statement and ResultSet have setFetchSize methods. If used with aStatement, all ResultSets returned by that Statement will have the same fetch size. Themethod can be used at any time to change the fetch size for a given ResultSet. Todetermine the current or default size, use the getFetchSize methods.Is there a practical limit for the number of SQL statements that can be added toan instance of a Statement objectWhile the specification makes no mention of any size limitation for Statement.addBatch(),this seems to be dependent, as usual, on the driver. Among other things, it depends onthe type of container/collection used. I know of at least one driver that uses a Vector andgrows as needed. Ive seen questions about another driver that appears to peaksomewhere between 500 and 1000 statements. Unfortunately, there doesnt appear to beany metadata information regarding possible limits. Of course, in a production qualitydriver, one would expect an exception from an addBatch() invocation that went beyondthe command lists limits.How can I determine whether a Statement and its ResultSet will be closed on acommit or rollback?Use the DatabaseMetaData methods supportsOpenStatementsAcrossCommit() andsupportsOpenStatementsAcrossRollback().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 ofreturning an updatable ResultSet. This is accomplished by asking the Connection toreturn the appropriate type of Statement using Connection.createStatement(intresultSetType, int resultSetConcurrency). The resultSetConcurrency parameter must beResultSet.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 © IT Engineering Portal : www.itportal.in 166
  • 167. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.INthat requested, depending on capabilities and circumstances, so the actual type returnedshould be checked with ResultSet.getConcurrency().How can I connect to an Oracle database not on the web server from anuntrusted applet?You can use the thin ORACLE JDBC driver in an applet (with some extra parameters onthe JDBC URL). Then, if you have NET8, you can use the connection manager of NET8on 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 commitConnection.setAutoCommit(false);//..your insert/update/delete goes hereConnection.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 supportsthese.How do I display and parse a date?The Java I18N way is to use a DateFormat. While SimpleDateFormat, which is generallyreturned, creates a large number of objects, it is locale aware and will handle most ofyour needs. The following sample code initially creates a java.sql.Date object and formatsit for the default locale. An initial actionPerformed call additionally formats/displays it fora 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.Dateimport java.sql.*;import javax.swing.*;import java.awt.*;import java.awt.event.*;import java.text.*;import java.util.*;public class JDFDP extends JFrameimplements ActionListener,WindowListener{// create a java.sql.Datejava.sql.Date jsqlDate = new java.sql.Date(System.currentTimeMillis() );DateFormat dfLocal = DateFormat.getDateInstance( © IT Engineering Portal : www.itportal.in 167
  • 168. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.INDateFormat.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 );pack();// set text by sending dummy eventjtI.setText( dfLocal.format( jsqlDate ) );actionPerformed(new ActionEvent( this, 12, "12" ) );show();} // end constructor// ActionListener Implementationpublic void actionPerformed(ActionEvent e){ © IT Engineering Portal : www.itportal.in 168
  • 169. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.INjtD.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.DatejsqlDate = new java.sql.Date( d.getTime() );jtP.setText( jsqlDate.toString() );}catch( ParseException pe ) { jtI.setText( "" ); }} // End actionPerformed// Window Listener Implementationpublic void windowOpened(WindowEvent e) {}public void windowClosing(WindowEvent e){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 Implementationpublic static void main(String[] args){new JDFDP();}} // end class JDFDPHow can I retrieve string data from a database in Unicode format?The data is already in Unicode when it arrivesin your program. Conversion from and to theencoding/charset/CCSID in the database from/toUnicode in the program is part of the JDBC drivers job. © IT Engineering Portal : www.itportal.in 169
  • 170. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.INIf, for some reason, you want to see the data inuHHHH 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();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";}elseif( iValue < 0x100 ){s = "u00";}elseif( iValue < 0x1000 ){s = "u0";}sb.append( s + Integer.toHexString( iValue ) );} // end forSystem.out.println("The Unicode format of " +args[0] + " is " + sb );} // end main} // end class UniFormatCan ResultSets be passed between methods of a class? Are there any specialusage © IT Engineering Portal : www.itportal.in 170
  • 171. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.INYes. There is no reason that a ResultSet cant be used as a method parameter just likeany other object reference. You must ensure that access to the ResultSet issynchronized. This should not be a problem is the ResultSet is a method variable passedas a method parameter - the ResultSet will have method scope and multi-thread accesswould not be an issue.As an example, say you have several methods that obtain a ResultSet from the sametable(s) and same columns, but use different queries. If you want these ResultSets to beprocessed the same way, you would have another method for that. This could looksomething 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 anygood state...) just because you received it as a parameter. Previous operations involvingthe 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 andCallableStatement/PreparedStatement/etcFrom my own experience using the Oracle JDBC drivers and CallableStatements thefollowing statements are true:* If you close the CallableStatement the ResultSet retrieved from that CallableStatementimmediately goes out-of-scope.* If you close the ResultSet without reading it fully, you must close the CallableStatementor risk leaking a cursor on the database server.* If you close the CallableStatement without reading its associated ResultSet fully, yourisk leaking a cursor on the database server.No doubt, these observations are valid only for Oracle drivers. Perhaps only for someversions of Oracle drivers. © IT Engineering Portal : www.itportal.in 171
  • 172. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.INThe 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 StatementHow 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 usePreparedStatement.setObject() or ResultSet.updateObject() methods for putting the arrayto an ARRAY in the database. Heres 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 storedprocedure?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 1cs.setInt(3, 3); // set the INOUT parm IO1 to 3cs.registerOutParameter(2, Types.INTEGER); // register the OUT parm O1cs.registerOutParameter(3, Types.INTEGER); // register the INOUT parm IO1cs.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 calledand 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 theserver side.How can I pool my database connections so I dont have to keep reconnecting tothe database?There are plenty of connection pool implementations described in books or availalble onthe net. Most of them implement the same model. The process is always the same : © IT Engineering Portal : www.itportal.in 172
  • 173. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.IN* 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 poolSince your application retrieves a pooled connection, you dont consume your time toconnect / disconnect from your data source. You can find some implementation ofpooled connection over the net, for example:* Db Connection Broker (http://www.javaexchange.com/), a package quite stable ( I usedit 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 whichdefines a number of additional concepts.How can I connect to an Excel spreadsheet file using jdbc?Lets say you have created the following Excel spreadsheet in a worksheet called Sheet1(the default sheet name). And youve saved the file in c:users.xls.USERID FIRST_NAME LAST_NAMEpkua Peter Kuajlsmith John Smithgh2312 Everett Johnsonchimera Faiz Abdullahroy6943 Roy SudirmanSince Excel comes with an ODBC driver, well use the JDBC-ODBC bridge driver thatcomes packaged with Suns JDK to connect to our spreadsheet.In Excel, the name of the worksheet is the equivalent of the database table name, whilethe header names found on the first row of the worksheet is the equivalent of the tablefield names. Therefore, when accessing Excel via jdbc, it is very important to place yourdata 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); © IT Engineering Portal : www.itportal.in 173
  • 174. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.IN}}public static void main(String args[]) {Connection conn=null;Statement stmt=null;String sql="";ResultSet rs=null;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 wouldconnect to any normal database server.The only significant difference is in the SELECT statement. Although your data isresiding in the worksheet called "Sheet1", youll have to refer to the sheet as Sheet1$ inyour SQL statements. And because the dollar sign symbol is a reserved character in SQL,youll have to encapsulate the word Sheet1$ in brackets, as shown in the code.How do I execute stored procedures?Here is an example on how to execute a stored procedure with JDBC (to use this in a © IT Engineering Portal : www.itportal.in 174
  • 175. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.INservlet is the same the only thing is that you create the connection and callablestatement 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 );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 ) );} © IT Engineering Portal : www.itportal.in 175
  • 176. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.INSystem.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 onlyproblem we encounter with JDBC-ODBC bridge is that a stored procedure pads spacesto the full length of a VARCHAR but the native JDBC behaves right. Therefore I suggestto 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 userwith the ability to enter any SQL statement, you dont know if you are going to get aResultSet 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:* true indicates next result is a ResultSetUse Statement.getResultSet to get the ResultSet* false indicates next result is an update countUse Statement.getUpdateCount to get the update count* false also indicates no more resultsUpdate count is -1 when no more results (usually 0 or positive)After processing each response, you use Statement.getMoreResults to check for moreresults, again returning a boolean. The following demonstrates the processing of multipleresult 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(); © IT Engineering Portal : www.itportal.in 176
  • 177. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.INupdateCount = 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 aResultSet 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: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 tryexperimenting 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 uploadedto 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 uploadthe 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) onyour hard drive. The first alternative solution is to create a digitally signed applet whichmay use locally installed JDBC drivers, able to connect directly to the database on theserver side.2. The easy way. Untrusted applets may only open a network connection to the serverfrom which they were downloaded. Thus, you must place a database listener (either thedatabase itself, or a middleware server) on the server node from which the applet wasdownloaded. The applet would open a socket connection to the middleware server,located on the same computer node as the webserver from which the applet wasdownloaded. The middleware server is used as a mediator, connecting to and extractdata 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 circumventthe security sandbox of the browser. © IT Engineering Portal : www.itportal.in 177
  • 178. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.INWhich is the preferred collection class to use for storing database result sets?When retrieving database results, the best collection implementation to use is theLinkedList. The benefits include:* Retains the original retrieval order* Has quick insertion at the head/tail* Doesnt have an internal size limitation like a Vector where when the size is exceeded anew 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 isalways synchronizedBasically: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, youll have to combine them into their owndata structure for each row. Arrays work well for that as you know the size, though acustom class might be best so you can convert the contents to the proper type whenextracting from databse, instead of later.The java.sql package contains mostly interfaces. When and how are theseinterfaces implemented while connecting to database?The implementation of these interfaces is all part of the driver. A JDBC driver is not justone class - it is a complete set of database-specific implementations for the interfacesdefined by the JDBC.These driver classes come into being through a bootstrap process. This is best shown bystepping through the process of using JDBC to connect to a database, using Oraclestype 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 codeblock) 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 theacceptsURL(String url) method of each driver, passing each the JDBC URL. The firstdriver 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 ofOracleDriver to obtain an instance of OracleConnection. It is this database-specificconnection instance implementing the Connection interface that is passed back from theDriverManager.getConnection() call.* The bootstrap process continues when you create a statement: © IT Engineering Portal : www.itportal.in 178
  • 179. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.INStatement statement = connection.createStatement();The connection reference points to an instance of OracleConnection. This database-specific implementation of Connection returns a database-specific implementation ofStatement, 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 thedatabase-specific details behind standard Java interfaces.How can I manage special characters (for example: " _ % ) when I execute anINSERT query? If I dont 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 notparsed or interpreted by the Java compiler. So there is no special mechanism for dealingwith special characters; if you need to use a quote (") within a Java string, you mustescape it.The Java programming language supports all the standard C escapes, such as n fornewline, t for tab, etc. In this case, you would use " to represent a quote within astring 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 ispassed on to the database. If you want tell the database to interpret characters like asingle quote () literally (and not as string delimiters, for instance), you need to use adifferent method. JDBC allows you to specify a separate, SQL escape character thatcauses the character following to be interpreted literally, rather than as a specialcharacter.An example of this is if you want to issue the following SQL command:SELECT * FROM BIRDSWHERE SPECIES=Williamsons SapsuckerIn this case, the apostrophe in "Williamsons" is going to cause a problem for thedatabase because SQL will interpret it as a string delimiter. It is not good enough to usethe C-style escape , because that substitution would be made by the Java compilerbefore the string is sent to the database.Different flavors of SQL provide different methods to deal with this situation. JDBCabstracts these methods and provides a solution that works for all databases. WithJDBC you could write the SQL as follows:Statement statement = // obtain reference to a Statement © IT Engineering Portal : www.itportal.in 179
  • 180. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.INstatement.executeQuery("SELECT * FROM BIRDS WHERE SPECIES=Williamson/s Sapsucker {escape /}");The clause in curly braces, namely {escape /}, is special syntax used to inform JDBCdrivers what character the programmer has chosen as an escape character. The forwardslash used as the SQL escape has no special meaning to the Java compiler; this escapesequence is interpreted by the JDBC driver and translated into database-specific SQLbefore the SQL command is issued to the database.Escape characters are also important when using the SQL LIKE clause. This usage isexplicitly addressed in section 11.5 of the JDBC specification:The characters "%" and "_" have special meaning in SQL LIKE clauses (to match zero ormore characters, or exactly one character, respectively). In order to interpret themliterally, they can be preceded with a special escape character in strings, e.g. "". In orderto specify the escape character used to quote these characters, include the followingsyntax on the end of the query:{escape escape-character}For example, the querySELECT NAME FROM IDENTIFIERS WHERE ID LIKE _% {escape }finds identifier names that begin with an underbar.How can I make batch updates using JDBC?One of the more advanced features of JDBC 2.0 is the ability to submit multiple updatestatements to the database for processing as a single unit. This batch updating can besignificantly more efficient compared to JDBC 1.0, where each update statement has tobe 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 exceptionint[] counts = be.getUpdateCounts();for (int i=0; I counts.length; i++) {System.out.println("Statement["+i+"] :"+counts[i]); © IT Engineering Portal : www.itportal.in 180
  • 181. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.IN}dbCon.rollback();}catch (SQLException e) {//handle SQL exceptiondbCon.rollback();}Before carrying out a batch update, it is important to disable the auto-commit mode bycalling setAutoCommit(false). This way, you will be able to rollback the batch transactionin case one of the updates fail for any reason. When the Statement object is created, it isautomatically associated a "command list", which is initially empty. We then add ourSQL update statements to this command list, by making successive calls to theaddBatch() method. On calling executeBatch(), the entire command list is sent over to thedatabase, and are then executed in the order they were added to the list. If all thecommands in the list are executed successfully, their corresponding update counts arereturned as an array of integers. Please note that you always have to clear the existingbatch by calling clearBatch() before creating a new one.If any of the updates fail to execute within the database, a BatchUpdateException isthrown in response to it. In case there is a problem in returning the update counts ofeach 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 investigatethe column type information of a particular table. Note that most arguments to thegetColumns method (pinpointing the column in question) may be null, to broaden thesearch 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 databaseConnection conn = DriverManager.getConnection("[jdbcURL]","[login]", "[passwd]");// Get DatabaseMetaDataDatabaseMetaData 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 © IT Engineering Portal : www.itportal.in 181
  • 182. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.INwhile(rs.next()){// Get dbObject metadataString 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);// PrintoutSystem.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 resourcesrs.close();conn.close();}How can I investigate the parameters to send into and receive from a databasestored procedure?Use the method getProcedureColumns in interface DatabaseMetaData to probe a storedprocedure for metadata. The exact usage is described in the code below.NOTE! This method can only discover parameter values. For databases where a returningResultSet 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 forthe JDBC metadata mining which is especially present when handling Transact-SQLdatabases 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 © IT Engineering Portal : www.itportal.in 182
  • 183. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.INConnection conn = DriverManager.getConnection("[jdbcURL]","[login]", "[passwd]");// Get DatabaseMetaDataDatabaseMetaData 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 theDBMS.");ResultSet rs = dbmd.getProcedureColumns("test", "dbo", "getFoodsEaten", "%");// Printout table datawhile(rs.next()){// Get procedure metadataString 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);// 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: © IT Engineering Portal : www.itportal.in 183
  • 184. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.INprocReturn = "return ResultSet";default:procReturn = "Unknown";}// PrintoutSystem.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 resourcesrs.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 getTablesmethod to retrieve information about all database objects (i.e. tables, views, systemtables, temporary global or local tables or aliases). The exact usage is described in thecode below.NOTE! Certain JDBC drivers throw IllegalCursorStateExceptions when you try to accessfields in the ResultSet in the wrong order (i.e. not consecutively). Thus, you should notchange 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 databaseConnection conn = DriverManager.getConnection("[jdbcURL]","[login]", "[passwd]");// Get DatabaseMetaDataDatabaseMetaData dbmd = conn.getMetaData();// Get all dbObjects. Replace the last argument in the getTables// method with objectCategories below to obtain only database © IT Engineering Portal : www.itportal.in 184
  • 185. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.IN// tables. (Sending in null retrievs all dbObjects).String[] objectCategories = {"TABLE"};ResultSet rs = dbmd.getTables(null, null, "%", null);// Printout table datawhile(rs.next()){// Get dbObject metadataString dbObjectCatalog = rs.getString(1);String dbObjectSchema = rs.getString(2);String dbObjectName = rs.getString(3);String dbObjectType = rs.getString(4);// PrintoutSystem.out.println("" + dbObjectType + ": " + dbObjectName);System.out.println(" Catalog: " + dbObjectCatalog);System.out.println(" Schema: " + dbObjectSchema);}// Close database resourcesrs.close();conn.close();}What does ResultSet actually contain? Is it the actual data of the result or somelinks to databases? If it is the actual data then why cant we access it afterconnection 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 isan 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 canhowever be processed like a ResultSet would be from the client. Closing a connectioncloses all interaction with the database and releases any locks that might have beenobtained in the process.How do I extract a BLOB from a database?A BLOB (Binary Large OBject) is essentially an array of bytes (byte[]), stored in thedatabase. You extract the data in two steps:1. Call the getBlob method of the Statement class to retrieve a java.sql.Blob object2. Call either getBinaryStream or getBytes in the extracted Blob object to retrieve the javabyte[] which is the Blob object.Note that a Blob is essentially a pointer to a byte array (called LOCATOR in database-talk), so the java.sql.Blob object essentially wraps a byte pointer. Thus, you must extractall data from the database blob before calling commit or © IT Engineering Portal : www.itportal.in 185
  • 186. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.IN<div align="center">private void runGetBLOB(){try{ // Prepare a Statement:PreparedStatement stmnt = conn.prepareStatement("select aBlob from BlobTable");// ExecuteResultSet rs = stmnt.executeQuery();while(rs.next()){try{// Get as a BLOBBlob aBlob = rs.getBlob(1);byte[] allBytesInBlob = aBlob.getBytes(1, (int) aBlob.length());}catch(Exception ex){// The driver could not handle this as a BLOB...// Fallback to default (and slower) byte[] handlingbyte[] bytes = rs.getBytes(1);}}// Close resourcesrs.close();stmnt.close();}catch(Exception ex){this.log("Error when trying to read BLOB: " + ex);}}</div>How do I extract the SQL statements required to move all tables and views froman 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 DatabaseMetaDatainterface.3. Create DDL SQL statements for re-creating the current database structure. Use theDatabaseMetaData interface. © IT Engineering Portal : www.itportal.in 186
  • 187. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.IN4. Build a dependency tree, to determine the order in which tables must be setup. Usethe 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 targetdatabase 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 thedatabase 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 databaseConnection conn = DriverManager.getConnection("[jdbcURL]","[login]", "[passwd]");// Get DatabaseMetaDataDatabaseMetaData dbmd = conn.getMetaData();// Get all table types.ResultSet rs = dbmd.getTableTypes();// Printout table datawhile(rs.next()){// PrintoutSystem.out.println("Type: " + rs.getString(1));}// Close database resourcesrs.close();conn.close();}What is the advantage of using a PreparedStatement?For SQL statements that are executed repeatedly, using a PreparedStatement objectwould almost always be faster than using a Statement object. This is because creating aPreparedStatement object by explicitly giving the SQL statement causes the statement tobe precompiled within the database immediately. Thus, when the PreparedStatement is © IT Engineering Portal : www.itportal.in 187
  • 188. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.INlater executed, the DBMS does not have to recompile the SQL statement and prepared anexecution 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 notaccept parameters.How do I find all database stored procedures in a database?Use the getProcedures method of interface java.sql.DatabaseMetaData to probe thedatabase 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 databaseConnection conn = DriverManager.getConnection("[jdbcURL]","[login]", "[passwd]");// Get DatabaseMetaDataDatabaseMetaData dbmd = conn.getMetaData();// Get all procedures.System.out.println("Procedures are called "+ dbmd.getProcedureTerm() +" in the DBMS.");ResultSet rs = dbmd.getProcedures(null, null, "%");// Printout table datawhile(rs.next()){// Get procedure metadataString 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 humansString procReturn = (dbProcedureType == DatabaseMetaData.procedureNoResult? "No Result" : "Result");// PrintoutSystem.out.println("Procedure: " + dbProcedureName+ ", returns: " + procReturn);System.out.println(" [Catalog | Schema]: [" + dbProcedureCatalog+ " | " + dbProcedureSchema + "]"); © IT Engineering Portal : www.itportal.in 188
  • 189. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.INSystem.out.println(" Comments: " + dbProcedureRemarks);}// Close database resourcesrs.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 SQLThe 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 codebelow: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 databaseConnection conn = DriverManager.getConnection("[jdbcURL]","[login]", "[passwd]");// Get DatabaseMetaDataDatabaseMetaData dbmd = conn.getMetaData();// Get all CatalogsSystem.out.println("nCatalogs are called " + dbmd.getCatalogTerm()+ " in this RDBMS.");processResultSet(dbmd.getCatalogTerm(), dbmd.getCatalogs());// Get all SchemasSystem.out.println("nSchemas are called " + dbmd.getSchemaTerm()+ " in this RDBMS.");processResultSet(dbmd.getSchemaTerm(), dbmd.getSchemas());// Get all Table-like typesSystem.out.println("nAll table types supported in this RDBMS:");processResultSet("Table type", dbmd.getTableTypes()); © IT Engineering Portal : www.itportal.in 189
  • 190. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.IN// Close the Connectionconn.close();}public static void processResultSet(String preamble, ResultSet rs)throws SQLException{// Printout table datawhile(rs.next()){// PrintoutSystem.out.println(preamble + ": " + rs.getString(1));}// Close database resourcesrs.close();}How does the Java Database Connectivity (JDBC) work?The JDBC is used whenever a Java application should communicate with a relationaldatabase for which a JDBC driver exists. JDBC is part of the Java platform standard; allvisible 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 fromthe java application with the proper database driver using communication subprotocol.The first driver that recognizes a certain subprotocol under jdbc (such as odbc ordbAnywhere/dbaw) will be used to establish a database Connection.* Driver. The database communications link, handling all communication with thedatabase. 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 beparsed, compiled, planned and executed.* ResultSet. The answer/result from a statement. A ResultSet is a fancy 2D list whichencapsulates 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), or2. Information about a specific ResultSet (java.sql.ResultSetMetaData).Use DatabaseMetaData to find information about your database, such as its capabilitiesand structure. Use ResultSetMetaData to find information about the results of an SQLquery, such as size and types of columns.How do I create a database connection?The database connection is created in 3 steps: © IT Engineering Portal : www.itportal.in 190
  • 191. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.IN1. Find a proper database URL (see FAQ on JDBC URL)2. Load the database driver3. Ask the Java DriverManager class to open a connection to your databaseIn 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 formore information). A JDBC URL has the formjdbc:someSubProtocol://myDatabaseServer/theDatabaseName2.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"); © IT Engineering Portal : www.itportal.in 191
  • 192. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.IN Oracle Interview Questions & AnswersOracle Interview Questions and Answers © IT Engineering Portal : www.itportal.in 192
  • 193. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.INWhat 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 moreredo log files, and one or more control files.What are the components of logical database structure of Oracle database?There are tablespaces and databases schema objects.What is a tablespace?A database is divided into Logical Storage Unit called tablespaces. A tablespace is used togrouped related logical structures together.What is SYSTEM tablespace and when is it created?Every Oracle database contains a tablespace named SYSTEM, which is automaticallycreated when the database is created. The SYSTEM tablespace always contains the datadictionary 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 areexplicitly 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 databases data.Schema objects include tables, views, sequences, synonyms, indexes, clusters, databasetriggers, 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 databasehold all of the user accessible data. Table data is stored in rows and columns.What is an Oracle view?A view is a virtual table. Every view has a query attached to it. (The query is a SELECTstatement 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 thedatabase is open or shut down.What is Mirrored on-line Redo Log ? © IT Engineering Portal : www.itportal.in 193
  • 194. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.INA mirrored on-line redo log consists of copies of on-line redo log files physically locatedon 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 andcontrol 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 identifythe database and redo log files that must be opened for database operation to proceed. Itis 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 ordeletion of referenced data. DELETE Cascade - When a referenced row is deleted allassociated 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 pseudocolumns 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 areexplicitly created for each tablespaceWhat are the different type of Segments ?Data Segment, Index Segment, Rollback Segment and Temporary Segment. © IT Engineering Portal : www.itportal.in 194
  • 195. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.INWhat are Clusters ?Clusters are groups of one or more tables physically stores together to share commoncolumns 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 atable.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 createdon 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.What is a View ?A view is a virtual table. Every view has a Query attached to it. (The Query is a SELECTstatement 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 databasehold 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 setof 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 adatabases 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. © IT Engineering Portal : www.itportal.in 195
  • 196. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.INWhat 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 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 createdon one or more columns of a table.How are the index updates?Indexes are automatically maintained and used by Oracle. Changes to table data areautomatically incorporated into all relevant indexes.What is a Tablespace?A database is divided into Logical Storage Unit called tablespace. A tablespace is used togrouped related logical structures togetherWhat 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 cantchange size. One or more data files form a logical unit of database storage called atablespace.How to define Data Block size ?A data block size is specified for each ORACLE database when the database is created. Adatabase users and allocated free database space in ORACLE data blocks. Block size isspecified 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 followinginformation.Database NameNames and locations of a databases files and redolog files.Time stamp of database creation.What is difference between UNIQUE constraint and PRIMARY KEY constraint ? © IT Engineering Portal : www.itportal.in 196
  • 197. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.INA column defined as UNIQUE can contain Nulls while a column defined as PRIMARY KEYcant contain Nulls.What is Index Cluster ?A Cluster with an index on the Cluster KeyWhen does a Transaction end ?When it is committed or Rollbacked.What is the effect of setting the value "ALL_ROWS" for OPTIMIZER_GOALparameter of the ALTER SESSION command ? What are the factors that affectOPTIMIZER in choosing an Optimization approach ?Answer The OPTIMIZER_MODE initialization parameter Statistics in the Data Dictionarythe OPTIMIZER_GOAL parameter of the ALTER SESSION command hints in thestatement.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 bestthroughput if statistics for atleast one of the tables accessed by the SQL statement existin 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" (DatabaseConfiguration Assistant) utility. The dbca utility is located in the $ORACLE_HOME/bindirectory. The Oracle Universal Installer (oui) normally starts it after installing thedatabase server software.One can also create databases manually using scripts. This option, however, is fallingout of fashion, as it is quite involved and error prone. Look at this example for creatingand Oracle 9i database:CONNECT SYS AS SYSDBAALTER 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 youroperating system block size. One can use smaller block sizes, but the performance cost issignificant. Your choice should depend on the type of application you are running. If youhave many small transactions as with OLTP, use a smaller block size. With fewer butlarger transactions, as with a DSS application, use a larger block size. If you are using avolume manager, consider your "operating system block size" to be 8K. This is becausevolume manager products use 8K blocks (and this is not configurable). © IT Engineering Portal : www.itportal.in 197
  • 198. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.INWhat are the different approaches used by Optimizer in choosing an executionplan ?Rule-based and Cost-based.What does ROLLBACK do ?ROLLBACK retracts any of the changes resulting from the SQL statements in thetransaction.How does one coalesce free space ? (for DBA)SMON coalesces free space (extents) into larger, contiguous extents every 2 hours andeven then, only for a short period of time.SMON will not coalesce free space if a tablespaces default storage parameter"pctincrease" is set to 0. With Oracle 7.3 one can manually coalesce a tablespace usingthe 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 theSYS.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 setPCTINCREASE to 1 you will see that your extents are going to have weird and wackysizes: 100K, 100K, 101K, 102K, etc. Such extents of bizarre size are rarely re-used intheir entirety. PCTINCREASE of 0 or 100 gives you nice round extent sizes that caneasily be reused. E.g.. 100K, 100K, 200K, 400K, etc.Use the same extent size for all the segments in a given tablespace. Locally Managedtablespaces (available from 8i onwards) with uniform extent sizes virtually eliminates anytablespace fragmentation. Note that the number of extents per segment does not causeany performance issue anymore, unless they run into thousands and thousands whereadditional I/O may be required to fetch the additional blocks where extent maps of thesegment 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. Atables HWM can be calculated using the results from the following SQL statements:SELECT BLOCKSFROM DBA_SEGMENTSWHERE OWNER=UPPER(owner) AND SEGMENT_NAME = UPPER(table);ANALYZE TABLE owner.table ESTIMATE STATISTICS;SELECT EMPTY_BLOCKSFROM DBA_TABLESWHERE OWNER=UPPER(owner) AND SEGMENT_NAME = UPPER(table);Thus, the tables HWM = (query result 1) - (query result 2) - 1NOTE: You can also use the DBMS_SPACE package and calculate the HWM =TOTAL_BLOCKS - UNUSED_BLOCKS - 1. © IT Engineering Portal : www.itportal.in 198
  • 199. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.INWhat is COST-based approach to optimization ?Considering available access paths and determining the most efficient execution planbased on statistics in the data dictionary for the tables accessed by the statement andtheir associated clusters and indexes.What does COMMIT do ?COMMIT makes permanent the changes resulting from all SQL statements in thetransaction. The changes made by the SQL statements of a transaction become visible toother 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 blocksare requested. If one requests 16K or 2 blocks (assuming a 8K block size), Oracle doesntround it up to 5 blocks, but it allocates 2 blocks or 16K as requested. If one asks for 8blocks, Oracle will round it up to 10 blocks.Space allocation also depends upon the size of contiguous free space available. If oneasks for 8 blocks and Oracle finds a contiguous free space that is exactly 8 blocks, itwould give it you. If it were 9 blocks, Oracle would also give it to you. Clearly Oracledoesnt always round extents to a multiple of 5 blocks.The exception to this rule is locally managed tablespaces. If a tablespace is created withlocal extent management and the extent size is 64K, then Oracle allocates 64K or 8blocks assuming 8K-block size. Oracle doesnt round it up to the multiple of 5 when atablespace 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 Acreate new user BImport system/manager fromuser=A touser=BDrop user ADefine Transaction ?A Transaction is a logical unit of work that comprises one or more SQL statementsexecuted by a single user.What is Read-Only Transaction ?A Read-Only transaction ensures that the results of each query executed in thetransaction 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 processthen deadlock arises. In a database environment this will often happen because of notissuing proper row lock commands. Poor design of front-end application may cause thissituation and the performance of server will reduce drastically.These locks will be released automatically when a commit/rollback operation performedor any one of this processes being killed externally. © IT Engineering Portal : www.itportal.in 199
  • 200. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.INWhat 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 indexedusing 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)What are the basic element of Base configuration of an oracle Database ?It consists ofone or more data files.one or more control files.two or more redo log files.The Database containsmultiple users/schemasone or more rollback segmentsone or more tablespacesData dictionary tablesUser objects (table,indexes,views etc.,)The server that access the database consists ofSGA (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)RECODispatcherUser Process with associated PGSWhat is clusters ?Group of tables physically stored together because they share common columns and areoften 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 atable. An index is automatically created when a unique of primary key constraint clauseis specified in create table comman (Ver 7.0)What is a Database instance ? ExplainA database instance (Server) is a set of memory structure and background processes thataccess a set of database files.The process can be shared by all users. The memory structure that are used to store © IT Engineering Portal : www.itportal.in 200
  • 201. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.INmost queried data from database. This helps up to improve database performance bydecreasing 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 datadictionary.- 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 timeavailable to the users session the CPU processing time available to a single call toORACLE made by a SQL statement the amount of logical I/O available to the userssession the amout of logical I/O available to a single call to ORACLE made by a SQLstatement the allowed amount of idle time for the users session the allowed amount ofconnect time for the users session.What is Tablespace Quota ?The collective amount of disk space available to the objects in a schema on a particulartablespace.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 tospecifically 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 databasetables. Export (EXP) and Import (imp) utilities allow you to move existing data inORACLE format to and from ORACLE database.How can you enable automatic archiving ?Shut the databaseBackup the databaseModify/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 © IT Engineering Portal : www.itportal.in 201
  • 202. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.INgroups of database users. Creating roles and assigning provides to roles. Assign each roleto 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 ofprivileges to many users a database administrator can grant the privileges for a group ofrelated 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, onlythe privileges of the role need to be modified. The security domains of all users grantedthe groups role automatically reflect the changes made to the role.SELECTIVE AVAILABILITY OF PRIVILEGES - The roles granted to a user can beselectively enable (available for use) or disabled (not available for use). This allowsspecific control of a users privileges in any given situation.APPLICATION AWARENESS - A database application can be designed to automaticallyenable 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 regardto specifically named objects.What is Object Auditing ?Object auditing is the auditing of accesses to specific schema objects without regard touser.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_$sessionWHERE Sid=1 /* this is pmon *//Users still running on Oracle 7 can try one of the following queries:Column STARTED format a18 head STARTUP TIMESelect 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) © IT Engineering Portal : www.itportal.in 202
  • 203. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.IN|| .|| Substr (to_char (mod (SEC.VALUE, 60), 09), 2, 2) STARTEDfrom SYS.V_$INSTANCE JUL,SYS.V_$INSTANCE SEC,SYS.V_$THREAD CWhere 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) STARTEDfrom SYS.V_$INSTANCE JUL,SYS.V_$INSTANCE SECwhere JUL.KEY like %JULIAN%and SEC.KEY like %SECOND%;select to_char (to_date (JUL.VALUE, J) + (SEC.VALUE/86400), -Return a DATEDD-MON-YY HH24:MI:SS) STARTEDfrom V$INSTANCE JUL,V$INSTANCE SECwhere JUL.KEY like %JULIAN%and SEC.KEY like %SECOND%;Where are my TEMPFILES, I dont 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. Insteadquery 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 inDBA_FREE_SPACE. Instead use the V$TEMP_SPACE_HEADER view:SELECT tablespace_name, SUM (bytes used), SUM (bytes free)FROM V$temp_space_headerGROUP BY tablespace_name;What is a profile ?Each database user is assigned a Profile that specifies limitations on various systemresources available to the user.How will you enforce security using stored procedures?Dont grant user access directly to tables within the application. Instead grant the abilityto access the procedures that access the tables. When procedure executed it will executethe 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 isfirst block of the segment. If your temporary tablespace is set to TEMPORARY, all sorts © IT Engineering Portal : www.itportal.in 203
  • 204. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.INare done in one large temporary segment. For usage stats, see SYS.V_$SORT_SEGMENTFrom 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.blocksfrom sys.v_$session s, sys.v_$sort_usage uwhere s.addr = u.session_addr/select s.osuser, s.process, s.username, s.serial#,Sum (u.blocks)*vp.value/1024 sort_sizefrom sys.v_$session s, sys.v_$sort_usage u, sys.v_$parameter VPwhere s.saddr = u.session_addrand vp.name = db_block_sizeand s.osuser like &1group 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_definitionWHERE view_name=V$SESSION;What are the dictionary tables used to monitor a database spaces ?DBA_FREE_SPACEDBA_SEGMENTSDBA_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 sequencenumber not padded. %T - Thread number lef-zero-paded and %t - Thread number notpadded). 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 importantrelationship 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 alreadyavailable) After giving table privileges. We cannot specify snapshot log name becauseoracle uses the name of the master table in the name of the database objects thatsupport its snapshot log. The master table name should be less than or equal to 23characters. (The table name created will be MLOGS_tablename, and trigger name will beTLOGS name).What dynamic data replication?Updating or Inserting records in remote database through database triggers. It may fail ifremote database is having any problem. © IT Engineering Portal : www.itportal.in 204
  • 205. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.INWhat is Two-Phase Commit ?Two-phase commit is mechanism that guarantees a distributed transaction eithercommits on all involved nodes or rolls back on all involved nodes to maintain dataconsistency across the global distributed database. It has two phase, a Prepare Phaseand 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 themanually immdiately locking the master tables. We can join tables in snopshots bycreating a complex snapshots that will based on the master tables.What is a SQL * NET?SQL *NET is ORACLEs mechanism for interfacing with the communication protocolsused by the networks that facilitate distributed processing and distributed databases. Itis 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 isperiodically refreshed to reflect changes made to the master table.What is the mechanism provided by ORACLE for table replication ?Snapshots and SNAPSHOT LOGsWhat is snapshots?Snapshot is an object used to dynamically replicate data between distribute database atspecified time intervals. In ver 7.0 they are read only.What are the various type of snapshots?Simple and Complex.Describe two phases of Two-phase commit ?Prepare phase - The global coordinator (initiating node) ask a participants to prepare (topromise 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 asksall nodes to commit the transaction, if all participants cannot prepare, the coordinatorasks 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. Itis stored in the same database as master table and is only available for simplesnapshots. 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 groupedtogether with others in a logical unit.Database uses a two phase commit. © IT Engineering Portal : www.itportal.in 205
  • 206. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.INWhat are the options available to refresh snapshots ?COMPLETE - Tables are completely regenerated using the snapshots query and themaster tables every time the snapshot referenced.FAST - If simple snapshot used then a snapshot log can be used to send the changes tothe snapshot tables.FORCE - Default value. If possible it performs a FAST refresh; Otherwise it will perform acomplete 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 mastertable. 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 serversthat appears to a user as single logical database. The data of all databases in thedistributed database can be simultaneously accessed and modified.How can we reduce the network traffic?- Replication of data in distributed environment.- 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 timeonly 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 thetransfer of information between users. It holds the most recently requested structuralinformation between users. It holds the most recently requested structural information © IT Engineering Portal : www.itportal.in 206
  • 207. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.INabout the database. The structure is database buffers, dictionary cache, redo log bufferand shared pool area.What is a shared pool?The data dictionary cache is stored in an area in SGA called the shared pool. This willallow 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.What is a data segment?Data segment are the physical areas within a database block in which the dataassociated 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 ratiois 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 commoncolumns 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 importantrelationship to the objects in the database and will be having certain privileges.How will you enforce security using stored procedures?Dont grant user access directly to tables within the application. Instead grant the abilityto access the procedures that access the tables. When procedure executed it will executethe 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_SPACEDBA_SEGMENTSDBA_DATA_FILES.Can a property clause itself be based on a property clause?Yes © IT Engineering Portal : www.itportal.in 207
  • 208. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.INIf 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?While both reports 2.0 and 2.5 create the parameter, report 2.5 gives a message that abind 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 itemWhat are the different windows events activated at runtimes?When_window_activatedWhen_window_closedWhen_window_deactivatedWhen_window_resizedWithin this triggers, you can examine the built in system variable system. event_windowto 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 nameof the record group defined in the current form. Data parameters are used to pass datato 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 remainsdisplayed, and operators can navigate between the forms as desired. when one forminvokes another form by executing call_form, the called form is modal with respect to thecalling form. That is, any windows that belong to the calling form are disabled, andoperators 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 firstform and releases its memory before loading the new form calling new form completelyreplace the first with the second. If there are changes pending in the first form, theoperator will be prompted to save them before the new form is loaded.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 thetext item to the values in the first column displayed in the LOV. Whenever the validationevent occurs. If the value in the text item matches one of the values in the first column ofthe LOV, validation succeeds, the LOV is not displayed, and processing continuesnormally. If the value in the text item does not match one of the values in the first © IT Engineering Portal : www.itportal.in 208
  • 209. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.INcolumn of the LOV, Oracle Forms displays the LOV and uses the text item value as thesearch 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 menuobjects 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 toreport 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. Thecontrols can use to obtain user inputs and display program outputs.vbx control whereoriginally develop as extensions for the ms visual basic environments and include suchitems as sliders, rides and knobs.What is the use of transactional triggers?Using transactional triggers we can control or modify the default functionality of theoracle 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,session). when invoke the multiple forms with open form and call_form in the sameapplication, state whether the following are true/FalseWhat 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 hierarchybetween them?Two group that is above are the left most rank higher than the group that is to right orbelow it.An open form can not be execute the call_form procedure if you chain of calledforms has been initiated by another open form?True © IT Engineering Portal : www.itportal.in 209
  • 210. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.INExplain about horizontal, Vertical tool bar canvas views?Tool bar canvas views are used to create tool bars for individual windows. Horizontal toolbars are display at the top of a window, just under its menu bar. Vertical Tool bars aredisplayed along the left side of a windowWhat 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 setand 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 anaction 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 flushesthe obsolete detail records. During the population phase, Oracle Forms issues a SELECTstatement to repopulate the detail block with detail records associated with the newmaster 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 detailsmaster with independent detailsdetail with two mastersWhat is a text list?The text list style list item appears as a rectangular box which displays the fixed numberof values. When the text list contains values that can not be displayed, a vertical scrollbar 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 usingr20run.What is use of term?The term file which key is correspond to which oracle report functions. © IT Engineering Portal : www.itportal.in 210
  • 211. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.INWhat 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 to7Bytes.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 binaryWhat are the Coordination Properties in a Master-Detail relationship?The coordination properties areDeferredAuto-QueryThese Properties determine when the population phase of blockcoordination 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 ofthe window to which it is assigned.To specify that the console should be displayed, setthe console window form property to the name of any window in the form. To include theconsole, set console window to Null.What are the different Parameter types?Text ParametersData ParametersState any three mouse events system variables?System.mouse_button_pressedSystem.mouse_button_shiftWhat 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 contentcanvas view assigned to that same window. Stacked canvas views obscure some part ofthe 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 secondarystorage (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; © IT Engineering Portal : www.itportal.in 211
  • 212. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.INselect name from sys.v_$controlfile;Sometimes Oracle takes forever to shutdown with the "immediate" option. Asworkaround to this problem, shutdown using these commands:alter system checkpoint;shutdown abortstartup restrictshutdown immediateNote that if you database is in ARCHIVELOG mode, one can still use archived log files toroll 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 modeand 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 inputstring and returns modified output string. Whereas the edit_textitem built-in needs theinput 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 anitem?set_item_propertyget_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 beforecopying 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 backupmode. Backing them up separately incurs less overhead. When done, remember tobackup your control files. Look at this example:ALTER SYSTEM SWITCH LOGFILE; -- Force log switch to update control file headersALTER DATABASE BACKUP CONTROLFILE TO /backupDir/control.dbf;NOTE: Do not run on-line backups during peak processing periods. Oracle will writecomplete database blocks instead of the normal deltas to redo log files while in backupmode. 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. Rmandoesnt put tablespaces in backup mode, saving on redo generation overhead. RMAN willre-read database blocks until it gets a consistent image of it. Look at this simple backupexample.rman target sys/*** nocatalogrun {allocate channel t1 type disk;backup © IT Engineering Portal : www.itportal.in 212
  • 213. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.INformat /app/oracle/db_backup/%d_t%t_s%s_p%p( database );release channel t1;}Example RMAN restore:rman target sys/*** nocatalogrun {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 basicconcepts. By default Oracle uses the database controlfiles to store information aboutbackups. Normally one would rather setup a RMAN catalog database to store RMANmetadata in. Read the Oracle Backup and Recovery Guide before implementing anyRMAN backups.Note: RMAN cannot write image copies directly to tape. One needs to use a third-partymedia manager that integrates with RMAN to backup directly to tape. Alternatively onecan 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 containsonly pcode. The resulting file can be used for final deployment, but can not besubsequently edited in the designer.ex. f45gen module=old_lib.pll userid=scott/tigerstrip_source YES output_fileHow does one put a database into ARCHIVELOG mode? (for DBA )The main reason for running in archivelog mode is that one can provide 24-houravailability and guarantee complete data recoverability. It is also necessary to enableARCHIVELOG mode before one can start to use on-line database backups. To enableARCHIVELOG mode, simply change your database startup command script, and bouncethe database:SQLPLUS> connect sys as sysdbaSQLPLUS> 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 archivelogmode. Without it one would not be able to recover. Also, implement an archivelog backupto prevent the archive log directory from filling-up.NOTE2: ARCHIVELOG mode was introduced with Oracle V6, and is essential fordatabase point-in-time recovery. Archiving can be used in combination with on-line and © IT Engineering Portal : www.itportal.in 213
  • 214. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.INoff-line database backups.NOTE3: You may want to set the following INIT.ORA parameters when enablingARCHIVELOG mode: log_archive_start=TRUE, log_archive_dest=... andlog_archive_format=...NOTE4: You can change the archive log destination of a database on-line with theARCHIVE LOG START TO directory; statement. This statement is often used to switcharchiving between a set of directories.NOTE5: When running Oracle Real Application Server (RAC), you need to shut down allnodes 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 fromfilling up. If the archive log directory becomes full, your database will hang! Look at thissimple RMAN backup script:RMAN> run {2> allocate channel dev1 type disk;3> backup4> format /app/oracle/arch_backup/log_t%t_s%s_p%p5> (archivelog all delete input);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 fileseven 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 enablereconstruction 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 multiplequeries?Read onlyWhat are the different types of Record Groups?Query Record GroupsNonQuery Record GroupsState Record Groups © IT Engineering Portal : www.itportal.in 214
  • 215. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.INFrom which designation is it preferred to send the output to the printed?PreviewerWhat are difference between post database commit and post-form commit?Post-form commit fires once during the post and commit transactions process, after thedatabase commit occurs. The post-form-commit trigger fires after inserts, updates anddeletes have been posted to the database but before the transactions have been finalizedin the issuing the command. The post-database-commit trigger fires after oracle formsissues the commit to finalized transactions.What are the different display styles of list items?Pop_listText_listCombo boxWhich of the above methods is the faster method?performing the calculation in the query is faster.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 thatare required by a form at startup. Form parameters are variables of typechar,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 consoleassignment at runtime.What is an administrative (privileged) user? (for DBA )Oracle DBAs and operators typically use administrative accounts to manage thedatabase and database instance. An administrative account is a user that is grantedSYSOPER or SYSDBA privileges. SYSDBA and SYSOPER allow access to a databaseinstance even if it is not running. Control of these privileges is managed outside of thedatabase via password files and special operating system groups. This password file iscreated 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_detailsHow does one connect to an administrative user? (for DBA )If an administrative user belongs to the "dba" group on Unix, or the "ORA_DBA" © IT Engineering Portal : www.itportal.in 215
  • 216. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.IN(ORA_sid_DBA) group on NT, he/she can connect like this:connect / as sysdbaNo password is required. This is equivalent to the desupported "connect internal"method.A password is required for "non-secure" administrative access. These passwords arestored in password files. Remote connections via Net8 are classified as non-secure. Lookat this example:connect sys/password as sysdbaHow does one create a password file? (for DBA )The Oracle Password File ($ORACLE_HOME/dbs/orapw or orapwSID) stores passwordsfor users with administrative privileges. One needs to create a password files beforeremote 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_SIDpassword=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 thecommand 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 inthe 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 thepassword file. New users can be added to the password file by granting them SYSDBA orSYSOPER 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 thecolumn?NoWhy 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 cannotbe 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 theremote 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 © IT Engineering Portal : www.itportal.in 216
  • 217. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.INEXTERNALLY will only be in effect from the local host. Also, if you are using "OPS$" asyour prefix, you will be able to log on locally with or without a password, regardless ofwhether you have identified your ID with a password or defined it to be IDENTIFIEDEXTERNALLY.Do user parameters appear in the data modal editor in 2.5?NoCan you pass data parameters to forms?NoIs it possible to link two groups inside a cross products after the cross productsgroup has been created?noWhat are the different modals of windows?Modalless windowsModal windowsWhat are modal windows?Modal windows are usually used as dialogs, and have restricted functionality comparedto modelless windows. On some platforms for example operators cannot resize, scroll oriconify a modal window.What are the different default triggers created when Master Deletes Property isset to Non-isolated?Master Deletes Property Resulting Triggers----------------------------------------------------Non-Isolated(the default) On-Check-Delete-MasterOn-Clear-DetailsOn-Populate-DetailsWhat are the different default triggers created when Master Deletes Property isset to isolated?Master Deletes Property Resulting Triggers---------------------------------------------------Isolated On-Clear-DetailsOn-Populate-DetailsWhat are the different default triggers created when Master Deletes Property isset to Cascade?Master Deletes Property Resulting Triggers---------------------------------------------------Cascading On-Clear-DetailsOn-Populate-DetailsPre-delete © IT Engineering Portal : www.itportal.in 217
  • 218. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.INWhat 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, lovcan have one or more columns.What is the advantage of the library?Libraries provide a convenient means of storing client-side program units and sharingthem among multiple applications. Once you create a library, you can attach it to anyother form, menu, or library modules. When you can call library program units fromtriggers menu items commands and user named routine, you write in the modules towhich you have attach the library. When a library attaches another library, programunits in the first library can reference program units in the attached library. Librarysupport dynamic loading-that is library program units are loaded into an applicationonly when needed. This can significantly reduce the run-time memory requirements ofapplications.What is lexical reference? How can it be created?Lexical reference is place_holder for text that can be embedded in a sql statements. Alexical reference can be created using & before the column or parameter name.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 toreflect 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 ofarguments 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 DDLHow 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 areselected and the link is automatically created. In 2.5 the first field is selected and thelink 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 © IT Engineering Portal : www.itportal.in 218
  • 219. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.INHow do you reference a Parameter?In Pl/Sql, You can reference and set the values of form parameters using bind variablessyntax. Ex. PARAMETER name = or :block.item = PARAMETER Parameter nameWhat is the difference between object embedding & linking in Oracle forms?In Oracle forms, Embedded objects become part of the form module, and linked objectsare 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_propertyWhat are the built-ins that are used for setting the LOV properties at runtime?get_lov_propertyset_lov_propertyWhat 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 canbe base on it?Four © IT Engineering Portal : www.itportal.in 219
  • 220. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.INTo execute row from being displayed that still use column in the row whichproperty can be used?Format trigger.What are different types of modules available in oracle form?Form module - a collection of objects and code routines Menu modules - a collection ofmenus and menu item commands that together make up an application menu librarymodule - a collection of user named procedures, functions and packages that can becalled from other modules in the applicationWhat is the remove on exit property?For a modelless window, it determines whether oracle forms hides the windowautomatically 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 firesas soon as oracle forms determines through validation that the record should beprocessed by the next post or commit as an insert or update. c generally occurs onlywhen the operators modifies the first item in the record, and after the operator attemptsto 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 constructsthe 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 databaseafter the operator as define the example records by entering the query criteria in enterquery mode.Pre-query trigger fires before pre-select trigger.What are built-ins associated with timers?find_timercreate_timerdelete_timerWhat 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 stackis allowed?FalseUse the Add_group_row procedure to add a row to a static record group 1. trueor false?False © IT Engineering Portal : www.itportal.in 220
  • 221. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.INWhat third party tools can be used with Oracle EBU/ RMAN? (for DBA)The following Media Management Software Vendors have integrated their mediamanagement software packages with Oracle Recovery Manager and Oracle7 EnterpriseBackup Utility. The Media Management Vendors will provide first line technical supportfor the integrated backup/recover solutions.Veritas NetBackupEMC Data Manager (EDM)HP OMNIBack IIIBMs Tivoli Storage Manager - formerly ADSMLegato NetworkerManageIT Backup and RecoverySterling Softwares SAMS:Alexandria - formerly from SpectralogicSun Solstice BackupWhy and when should one tune? (for DBA)One of the biggest responsibilities of a DBA is to ensure that the Oracle database istuned properly. The Oracle RDBMS is highly tunable and allows the database to bemonitored and adjusted to increase its performance. One should do performance tuningfor the following reasons:The speed of computing might be wasting valuable human time (users waiting forresponse); Enable your system to keep-up with the speed business is conducted; andOptimize hardware usage to save money (companies are spending millions on hardware).Although this FAQ is not overly concerned with hardware issues, one needs to rememberthan you cannot tune a Buick into a Ferrari.How can a break order be created on a column in an existing group? What arethe 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 amouse double click event involves?A placeholder column is used to hold calculated values at a specified place rather thanallowing is to appear in the actual row where it has to appear.What is the use of hidden column? What are the various sub events a mousedouble 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 aspectsof a database. Writing custom scripts, implementing Oracles Enterprise Manager, orbuying a third-party monitoring product can achieve this. If an alarm is triggered, thesystem should automatically notify the DBA (e-mail, page, etc.) to take appropriateaction.Infrastructure availability:. Is the database up and responding to requests. Are the listeners up and responding to requests © IT Engineering Portal : www.itportal.in 221
  • 222. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.IN. Are the Oracle Names and LDAP Servers up and responding to requests. Are the Web Listeners up and responding to requestsThings that can cause service outages:. Is the archive log destination filling up?. Objects getting close to their max extents. User and process limits reachedThings 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 bemaintained to prevent tuning side effects. For example, it is no good increasing the buffercache if you can reduce I/O by rewriting a SQL statement. Database Design (if its nottoo late):Poor system performance usually results from a poor database design. One shouldgenerally normalize to the 3NF. Selective denormalization can provide valuableperformance improvements. When designing, always keep the "data access path" inmind. Also look at proper data partitioning, data replication, aggregation tables fordecision support systems, etc.Application Tuning:Experience showed that approximately 80% of all Oracle system performance problemsare resolved by coding optimal SQL. Also consider proper scheduling of batch tasks afterpeak working hours.Memory Tuning:Properly size your database buffers (shared pool, buffer cache, log buffer, etc) by lookingat 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 disksubsystem throughput. Also look for frequent disk sorts, full table scans, missingindexes, row chaining, data fragmentation, etcEliminate 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 moreinformation, read the related Oracle FAQ dealing with your specific operating system.What are the various sub events a mouse double click event involves? What arethe various sub events a mouse double click event involves?Double clicking the mouse consists of the mouse down, mouse up, mouse click, mousedown & 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. © IT Engineering Portal : www.itportal.in 222
  • 223. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.INWhat 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 viewsStacked canvas viewsHorizontal toolbarvertical toolbar.What are the different types of Delete details we can establish in Master-Details?CascadeIsolateNon-isolateWhat is relation between the window and canvas views?Canvas views are the back ground objects on which you place the interface items (Textitems), 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 awindow.What is a User_exit?Calls the user exit named in the user_exit_string. Invokes a 3Gl program by name whichhas been properly linked into your current oracle forms executable.How is it possible to select generate a select set for the query in the queryproperty sheet?By using the tables/columns button and then specifying the table and the columnnames.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 dropthese tables to get rid of the old data. If not, the new data will be appended to the © IT Engineering Portal : www.itportal.in 223
  • 224. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.INexisting tables. One must always DROP existing Sequences before re-importing. If thesequences are not dropped, they will generate numbers inconsistent with the rest of thedatabase. Note: It is also advisable to drop indexes before importing to speed up theimport process. Indexes can easily be recreated after the data was successfully imported.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 theSRW.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 cantake an export file created from an old export version, and import it using a later versionof the import utility. This is quite an effective way of upgrading a database from onerelease of Oracle to the next.Oracle also ships some previous catexpX.sql scripts that can be executed as user SYSenabling older imp/exp versions to work (for backwards compatibility). For example, onecan run $ORACLE_HOME/rdbms/admin/catexp7.sql on an Oracle 8 database to allowthe Oracle 7.3 exp/imp utilities to run against an Oracle 8 database.What are different types of images?Boiler plate imagesImage ItemsCan 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 enableslarge exports to be divided into files whose sizes will not exceed any operating systemlimits (FILESIZE= parameter). When importing from multi-file export you must providethe 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.logUse 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 canexport up to 10 gigabytes to a single file. This example uses gzip. It offers the bestcompression I know of, but you can also substitute it with zip, compress or whatever.# create a named pipemknod exp.pipe p# read the pipe - output to zip file in the backgroundgzip < exp.pipe > scott.exp.gz &# feed the pipeexp 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 bindreference can be created using a (:) before a column or a parameter name.How can one improve Import/ Export performance? (for DBA)EXPORT:. Set the BUFFER parameter to a high value (e.g. 2M) © IT Engineering Portal : www.itportal.in 224
  • 225. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.IN. 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. Dothis by setting INDEXFILE to a filename and then import. No data will be imported but afile containing index definitions will be created. You must edit this file afterwards andsupply 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 theinit$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 rollbacksegments offline (except the SYSTEM rollback segment of course). The rollback segmentmust 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 ANALYZEstatements. Remember to run the indexfile previously createdGive 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. UseIGNORE=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 exportingor use parameter CONSISTENT=NOORA-01562: Failed to extend rollback segment - Create bigger rollback segments or setparameter COMMIT=Y while importingIMP-00015: Statement failed ... object already exists... - Use the IGNORE=Y importparameter to ignore these errors, but be careful as you might end up with duplicaterows.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, executeand fetch data.Where is the external query executed at the client or the server?At the server. © IT Engineering Portal : www.itportal.in 225
  • 226. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.INWhere is a procedure return in an external pl/sql library executed at the clientor 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 acoordination causing event.What is the difference between OLE Server & Ole Container?An Ole server application creates ole Objects that are embedded or linked in oleContainers ex. Ole servers are ms_word & ms_excel. OLE containers provide a place tostore, 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 whenyou want to package related objects, so that you copy or reference them in othermodules.What is an LOV?An LOV is a scrollable popup window that provides the operator with either a single ormulti 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 aredisplayed.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 anotherOracle 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 displaysize, position, and title.My database was terminated while in BACKUP MODE, do I need to recover? (forDBA)If a database was terminated while one of its tablespaces was in BACKUP MODE (ALTERTABLESPACE xyz BEGIN BACKUP;), it will tell you that media recovery is required whenyou try to restart the database. The DBA is then required to recover the database andapply all archived logs to the database. However, from Oracle7.2, you can simply take the © IT Engineering Portal : www.itportal.in 226
  • 227. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.INindividual 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. Thisnormally 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 datafilesout 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 androw 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/rowframework similar to a database table. However, unlike database tables, record groupsare 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 cansometimes extract data from an offline database using a utility called DUL (DiskUnLoad). This utility reads data in the data files and unloads it into SQL*Loader orexport 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 anabsolute last resort and will most likely cost your company a lot of money!!!Ive 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 arecorrupted or blown away. Caution is advised when enabling this parameter as you mightend-up losing your entire database. Please contact Oracle Support before using it._allow_resetlogs_corruption = trueWhat 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 aproperty can inherit the setting of any property in the clause that makes sense for thatobject.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 thesize of one page of the actual report as seen in the Previewer.Ive 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 rollbacksegments is corrupted. You can then drop the corrupted rollback segments and create itfrom scratch. © IT Engineering Portal : www.itportal.in 227
  • 228. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.INCaution is advised when enabling this parameter, as uncommitted transactions will bemarked as committed. One can very well end up with lost or inconsistent data!!! Pleasecontact 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 forbacking up Oracle7 databases. It is sometimes referred to as OEBU for Oracle EnterpriseBackup Utility. The Oracle Recovery Manager (RMAN) utility that ships with Oracle8 andabove is similar to Oracle7s EBU utility. However, there is no direct upgrade path fromEBU to RMAN.How does one create a RMAN recovery catalog? (for DBA)Start by creating a database schema (usually called rman). Assign an appropriatetablespace to it and grant it the recovery_catalog_owner role. Look at this example:sqlplus sysSQL>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 byrunning the catrman.sql script. rman catalog rman/rmanRMAN>create catalog tablespace tools;RMAN> exit;You can now continue by registering your databases in the catalog. Look at thisexample:rman catalog rman/rman target backdba/backdbaRMAN> register database;How can a group in a cross products be visually distinguished from a group thatdoes 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 ofrecords 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 thepop list or the text list style list items, the combo box style list item will both display fixedvalues and accept one operator entered value.What are three panes that appear in the run time pl/sql interpreter?1. Source pane.2. interpreter pane.3. Navigator pane. © IT Engineering Portal : www.itportal.in 228
  • 229. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.INWhat are the two panes that Appear in the design time pl/sql interpreter?1. Source pane.2. Interpreter paneWhat are the two ways by which data can be generated for a parameters list ofvalues?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,.mmxWhat are the default extensions of the files created by forms modules?.fmb - form module binary.fmx - form module executableTo 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 overfile. 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 tarcommand cannot be used for physical file backup, instead we can use dd commandwhich is less flexible and has limited recoveries.What is the significance of having storage clause ?We can plan the storage for a table as how much initial extents are required, how muchcan 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 thesequence of events when a large transaction that exceeds beyond its optimal value whenan entry wraps and causes the rollback segment toexpand into anotion Completes. e. willbe written.What is the use of FILE option in IMP command ?The name of the file from which import should be performed. © IT Engineering Portal : www.itportal.in 229
  • 230. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.INWhat is a Shared SQL pool?The data dictionary cache is stored in an area in SGA called the Shared SQL Pool. Thiswill 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 ARCHIVELOGmode should be enabled. The following files need to be backed up. All data files. AllArchive log, redo log files. All control files.List the Optional Flexible Architecture (OFA) of Oracle database? or How can weorganize the tablespaces in Oracle database to have maximum performance ?SYSTEM - Data dictionary tables.DATA - Standard operational tables.DATA2- Static tables used for standard operationsINDEXES - 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 tablespaceTEMP_USER - Temporary tablespace for users.USERS - User tablespace.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 Configora 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 OperatingSystem 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/Orequest to use the shadow set of files instead of the main set of files. This reduces I/Oload 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 singletransaction 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. © IT Engineering Portal : www.itportal.in 230
  • 231. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.INHow will you monitor rollback segment status ?Querying the DBA_ROLLBACK_SEGS viewIN USE - Rollback Segment is on-line.AVAILABLE - Rollback Segment available but not on-line.OFF-LINE - Rollback Segment off-lineINVALID - Rollback Segment Dropped.NEEDS RECOVERY - Contains data but need recovery or corupted.PARTLY AVAILABLE - Contains data from an unresolved transaction involving adistributed 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 bycreating group of log files together, so that LGWR will automatically writes them to all themembers of the current on-line redo log group. If any one group fails then databaseautomatically switch over to next group. It degrades performance.Which parameter in Storage clause will reduce no. of rows per block?PCTFREE parameterRow 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 theSHARED_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? (forDBA)A latch is an internal Oracle mechanism used to protect data structures in the SGA fromsimultaneous access. Atomic hardware instructions like TEST-AND-SET is used toimplement latches. Latches are more restrictive than locks in that they are alwaysexclusive. 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 andconcurrency. They are queued and serviced in a first-in-first-out (FIFO) order.Semaphores are an operating system facility used to control waiting. Semaphores arecontrolled by the following Unix parameters: semmni, semmns and semmsl. Typicalsettings are:semmns = sum of the "processes" parameter for each instance(see init<instance>.ora for each instance)semmni = number of instances running simultaneously;semmsl = semmnsWhat is a logical backup?Logical backup involves reading a set of database records and writing them into a file. © IT Engineering Portal : www.itportal.in 231
  • 232. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.INExport utility is used for taking backup and Import utility is used to recover frombackup.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 orunsupported parameters. One can get a list of all hidden parameters by executing thisquery:select *from SYS.X$KSPPIwhere 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 cwhere a.indx = b.indx and a.indx = c.indxand 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 followingtwo examples are simply to demonstrate syntax. Refer to later notes on this page for anexplanation 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 users current session, whereas changes to theINIT.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 atransaction. Each Rollback Segment entry must be completed within one rollbacksegment. 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 diagnoseproblems:" 10046 trace name context forever, level 4 Trace SQL statements and show bindvariables 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 andwait events in the SQL trace files" 1401 trace name errorstack, level 12 1401 trace name errorstack, level 4 1401 tracename processstate Dumps out trace information if an ORA-1401 "inserted value too largefor column" error occurs. The 1401 can be replaced by any other Oracle Server error codethat you want to trace." 60 trace name errorstack level 10 Show where in the code Oracle gets a deadlock (ORA- © IT Engineering Portal : www.itportal.in 232
  • 233. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.IN60), and may help to diagnose the problem.The following lists of events are examples only. They might be version specific, so pleasecall Oracle before using them:" 10210 trace name context forever, level 10 10211 trace name context forever, level 1010231 trace name context forever, level 10 These events prevent database blockcorruptions" 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 forconnectionsNote: 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 informationabout internal database structures.o Dump control file contentsalter session set events immediate trace name CONTROLF level 10/o Dump file headersalter session set events immediate trace name FILE_HDRS level 10/o Dump redo log headersalter session set events immediate trace name REDOHDR level 10/o Dump the system stateNOTE: Take 3 successive SYSTEMSTATE dumps, with 10-minute intervals alter sessionset events immediate trace name SYSTEMSTATE level 10/o Dump the process statealter session set events immediate trace name PROCESSSTATE level 10/o Dump Library Cache detailsalter session set events immediate trace name library cache level 10/o Dump optimizer statistics whenever a SQL statement is parsed (hint: change statementor 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 fileand block number to a DBA (database block address).Eg: variable x varchar2;exec :x := dbms_utility.make_data_block_address(1,12);print xalter session set events immediate trace name blockdump level 50360894/ © IT Engineering Portal : www.itportal.in 233
  • 234. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.INWhat are the different kind of export backups?Full back - Complete databaseIncremental - 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.0What is the use of RECORD option in EXP command?For Incremental exports, the flag indirects whether a record will be stores data dictionarytables 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 thedatabase objects will be created.What is the use of COMPRESS option in EXP command ?Flag to indicate whether export should compress fragmented segments into singleextents.How will you swap objects into a different table space for an existing database ?Export the userPerform import using the command imp system/manager file=export.dmpindexfile=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 followsFixed block headerVariable block headerRow 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 placewhile executing SQL statements. If the ratio is greater than 1 then increase theSHARED_POOL_SIZE. LOGICAL & PHYSICAL ARCHITECTURE OF DATABASE.What is dictionary cache ?Dictionary cache is information about the databse objects stored in a data dictionarytable.What is a Control file ?Database overall physical architecture is maintained in a file called control file. It will be © IT Engineering Portal : www.itportal.in 234
  • 235. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.INused to maintain internal consistency and guide recovery operations. Multiple copies ofcontrol files are advisable.What is Database Buffers ?Database buffers are cache in the SGA used to hold the data blocks that are read fromthe data segments in the database such as tables, indexes and clustersDB_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 SYSTEMtablespace. Create a Second Rollback Segment name R0 in the SYSTEM tablespace.Make new rollback segment available (After shutdown, modify init.ora file and Startdatabase) Create other tablespaces (RBS) for rollback segments. Deactivate RollbackSegment 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. Weneed 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 beused in roll forward operations during database recoveries. Before writing them into theredo log files, they will first brought to redo log buffers in SGA and LGWR will write intofiles frequently. LOG_BUFFER parameter will decide the size.How will you estimate the space required by a non-clustered tables?Calculate the total header sizeCalculate the available dataspace per data blockCalculate the combined column lengths of the average rowCalculate the total average row size.Calculate the average number rows that can fit in a blockCalculate the number of blocks and bytes required for the table.After arriving the calculation, add 10 % additional space to calculate the initial extentsize 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 isdropped its extents are reallocated and are marked as free. © IT Engineering Portal : www.itportal.in 235
  • 236. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.INWhat is the use of IGNORE option in IMP command ?A flag to indicate whether the import should ignore errors encounter when issuingCREATE commands.What is the use of ANALYSE ( Ver 7) option in EXP command ?A flag to indicate whether statistical information about the exported objects should bewritten 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 fordatabase 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 Yor 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 bemaintained.What are the different methods of backing up oracle database ?- Logical Backups- Cold Backups- Hot Backups (Archive log)What is the difference between ON-VALIDATE-FIELD trigger and a POST-CHANGEtrigger ?When you changes the Existing value to null, the On-validate field trigger will fire post © IT Engineering Portal : www.itportal.in 236
  • 237. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.INchange 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 ?UnlimitedWhile specifying master/detail relationship between two blocks specifying thejoin condition is a must ?True or False. ?TrueEXIT_FORM is a restricted package procedure ?a. True b. FalseTrueWhat is the usage of an ON-INSERT,ON-DELETE and ON-UPDATE TRIGGERS ?These triggers are executes when inserting, deleting and updating operations areperformed and can be used to change the default function of insert, delete or updaterespectively. For Eg, instead of inserting a row in a table an existing row can be updatedin the same table.What are the types of Pop-up window ?the pop-up field editorpop-up list of valuespop-up pages.Alert :What is an SQL *FORMS ?SQL *forms is 4GL tool for developing and executing; Oracle based interactiveapplication.How do you control the constraints in forms ?Select the use constraint property is ON Block definition screen.BLOCKWhat is the difference between restricted and unrestricted package procedure ?Restricted package procedure that affects the basic functions of SQL * Forms. It cannotused in all triggers except key triggers. Unrestricted package procedure that does notinterfere with the basic functions of SQL * Forms it can be used in any triggers. © IT Engineering Portal : www.itportal.in 237
  • 238. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.INA query fetched 10 records How many times does a PRE-QUERY Trigger andPOST-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 thefollowing 3 triggers are defined at the same block level ?a. ON-INSERT b. POST-INSERT c. PRE-INSERTState 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 keyWhat do you mean by a page ?Pages are collection of display information, such as constant text and graphicsWhat are the type of User Exits ?ORACLE Precompliers user exitsOCI (ORACLE Call Interface)Non-ORACEL user exits.Page :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 ?NoIs a Key startup trigger fires as result of a operator pressing a key explicitly ?NoCan we use GO-BLOCK package in a pre-field trigger ?NoCan we create two blocks with the same name in form 3.0 ?NoWhat 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 filexextension ? © IT Engineering Portal : www.itportal.in 238
  • 239. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.ININP (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 KeyKey-functionKey-othersKey-startupWhat is the difference between a Function Key Trigger and Key Function Trigger?Function key triggers are associated with individual SQL*FORMS function keys You canattach Key function triggers to 10 keys or key sequences that normally do not performany SQL * FORMS operations. These keys referred as key F0 through key F9.Committed block sometimes refer to a BASE TABLE ?FalseError_Code is a package proecdure ?a. True b. falseFalseWhen is cost based optimization triggered? (for DBA)Its important to have statistics on all tables for the CBO (Cost Based Optimizer) to workcorrectly. If one table involved in a statement does not have statistics, Oracle has torevert to rule-based optimization for that statement. So you really want for all tables tohave statistics right away; it wont 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 entriesfrom the index instead of the table. This can be done by specifying hints. If the index isphysically smaller than the table (which is usually the case) it will take less time to scanthe entire index than to scan the entire table.What Enter package procedure does ?Enter Validate-data in the current validation unit. © IT Engineering Portal : www.itportal.in 239
  • 240. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.INWhere 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 thetablespace has the most I/O. The $ORACLE_HOME/rdbms/admin/catio.sql scriptcreates a sample_io procedure and table to gather the required information. Afterexecuting the procedure, one can do a simple SELECT * FROM io_per_object; to extractthe required information. For more details, look at the header comments in the$ORACLE_HOME/rdbms/admin/catio.sql script.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 currentexplain plan of the offending query and compare it to a previous one that was takenwhen 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 queryusing 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 producesthe 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 CostBased Optimizer. The usual cause is because the CBO calculates that executing a FullTable 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 distinctvalues the column holds.. USER_TABLES.NUM_ROWS - If NUM_DISTINCT = NUM_ROWS then using an indexwould be preferable to doing a FULL TABLE SCAN. As the NUM_DISTINCT decreases, thecost of using an index increase thereby is making the index less desirable.. USER_INDEXES.CLUSTERING_FACTOR - This defines how ordered the rows are in theindex. If CLUSTERING_FACTOR approaches the number of blocks in the table, the rowsare ordered. If it approaches the number of rows in the table, the rows are randomlyordered. In such a case, it is unlikely that index entries in the same leaf block will pointto rows in the same data blocks.. Decrease the INIT.ORA parameter DB_FILE_MULTIBLOCK_READ_COUNT - A highervalue will make the cost of a FULL TABLE SCAN cheaper.. Remember that you MUST supply the leading column of an index, for the index to beused (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 toshow why an index is not being used by the CBO. If from checking the above you still feel © IT Engineering Portal : www.itportal.in 240
  • 241. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.INthat the query should be using an index, try specifying an index hint. Obtain an explainplan of the query either using TKPROF with TIMED_STATISTICS, so that one can see theCPU utilization, or with AUTOTRACE to see the statistics. Compare this to the explainplan when not using an index.When should one rebuild an index? (for DBA)You can run the ANALYZE INDEX VALIDATE STRUCTURE command on the affectedindexes - each invocation of this command creates a single row in the INDEX_STATSview. This row is overwritten by the next ANALYZE INDEX command, so copy thecontents of the view into a local table after each ANALYZE. The badness of the index canthen be judged by the ratio of DEL_LF_ROWS to LF_ROWS.What are the unrestricted procedures used to change the popup screen positionduring run time ?Anchor-viewResize -ViewMove-View.What is an Alert ?An alert is window that appears in the middle of the screen overlaying a portion of thecurrent display.Deleting a page removes information about all the fields in that page ?a. True. b. Falsea. True.Two popup pages can appear on the screen at a time ?Two popup pages canappear on the screen at a time ?a. True. b. False?a. True.Classify the restricted and unrestricted procedure from the following.a. Callb. User-Exitc. Call-Queryd. Upe. Execute-Queryf. Messageg. Exit-Fromh. Posti. Break?a. Call - unrestrictedb. User Exit - Unrestrictedc. Call_query - Unrestrictedd. Up - Restrictede. Execute Query - Restricted © IT Engineering Portal : www.itportal.in 241
  • 242. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.INf. Message - Restrictedg. Exit_form - Restrictedh. Post - Restrictedi. 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_status2. System.current_block3. System.current_field4. System.current_value5. System.cursor_block6. System.cursor_field7. 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-Code2. Break3. Call4. Error-text5. Form-failure6. Form-fatal7. Execute-query © IT Engineering Portal : www.itportal.in 242
  • 243. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.IN8. Anchor View9. Message_code?1. Error_Code2. Error_Text3. Form_Failure4. Form_Fatal5. Message_CodeCan you attach an lov to a field at run-time? if yes, give the build-in name.?Yes. Set_item_propretyIs it possible to attach same library to more than one form?YesCan you attach an lov to a field at design time?YesList the windows event triggers available in Forms 4.0?When-window-activated,when-window-closed,when-window-deactivated,when-window-resizedWhat 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 operatorssee 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 groupHow 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 thefollowing steps in a trigger or user named routine execute the create_parameter_listbuilt-in function to programmatically. Create a parameter list to execute the addparameter 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 parameterlist 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 andboilerplate text and graphics objects in your applications interface. © IT Engineering Portal : www.itportal.in 243
  • 244. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.INList the Types of Items?Text item.Chart item.Check box.Display item.Image item.List item.Radio Group.User Area item.List system variables available in forms 4.0, and not available in forms 3.0?System.cordination_operationSystem Date_thresholdSystem.effective_DateSystem.event_windowSystem.suppress_workingWhat are the display styles of an alert?Stop, Caution, noteWhat 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_propertyCanvas-ViewWhat are the different types of windows?Root window, secondary window.What is a predefined exception available in forms 4.0?Raise form_trigger_failureWhat is a radio Group?Radio groups display a fixed no of options that are mutually Exclusive. User can selectone out of n number of options.What are the different type of a record group?Query record groupStatic record groupNon query record groupWhat are the menu items that oracle forms 4.0 supports?Plain, Check,Radio, Separator, Magic © IT Engineering Portal : www.itportal.in 244
  • 245. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.INGive the equivalent term in forms 4.0 for the following. Page, Page 0?Page - Canvas-ViewPage 0 - Canvas-view null.What triggers are associated with the radio group?Only when-radio-changed trigger associated with radio groupVisual 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?NoCan a root window be made modal?NoWhat is a list item?It is a list of text elements.List some built-in routines used to manipulate images in image_item?Image_addImage_andImage_subtractImage_xorImage_zoomCan 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_propertySet_lov_propertyRecord GroupWhat is the built-in routine used to count the no of rows in a group?Get_group _row_countSystem VariablesGive the Types of modules in a form?FormMenuLibraryWrite the Abbreviation for the following File Extension 1. FMB 2. MMB 3. PLL?FMB ----- Form Module Binary. © IT Engineering Portal : www.itportal.in 245
  • 246. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.INMMB ----- 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_ViewList the built-in routine for controlling window during run-time?Find_canvasGet-Canvas_propertyGet_view_propertyHide_ViewReplace_content_viewScroll_viewSet_canvas_propertySet_view_propertyShow_viewAlertWhat is the built-in function used for finding the alert?Find_alertEditorsList the editors availables in forms 4.0?Default editorUser_defined editorssystem editors.What buil-in routines are used to display editor dynamically?Edit_text itemshow_editorLOVWhat is an Lov?A list of values is a single or multi column selection list displayed in a pop-up windowWhat is a record Group?A record group is an internal oracle forms data structure that has a similar column/rowframe work to a database tableGive built-in routine related to a record groups?Create_group (Function) © IT Engineering Portal : www.itportal.in 246
  • 247. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.INCreate_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_canvasGet-Canvas_propertyGet_view_propertyHide_ViewReplace_content_viewScroll_viewSet_canvas_propertySet_view_propertyShow_viewAlertSystem.effective_date system variable is read only True/False?FalseWhat are the built_in used to trapping errors in forms 4?Error_type return characterError_code return numberError_text return charDbms_error_code return no.Dbms_error_text return charWhat 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, OracleFinancials can meet accounting management demands with:Oracle Assets: Ensures that an organizations property and equipment investment isaccurate 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 minimizingstock and maximizing cash flow.Oracle Order Entry: Provides organizations with a sophisticated order entry system formanaging customer commitments.Oracle Payables: Lets an organization process more invoices with fewer staff membersand tighter controls. Helps save money through maximum discounts, bank float, andprevention of duplicate payment.Oracle Personnel: Improves the management of employee- related issues by retaining and © IT Engineering Portal : www.itportal.in 247
  • 248. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.INmaking available every form of personnel data.Oracle Purchasing: Improves buying power, helps negotiate bigger discounts, eliminatespaper flow, increases financial controls, and increases productivity.Oracle Receivables:. Improves cash flow by letting an organization process morepayments faster, without off-line research. Helps correctly account for cash, reduceoutstanding receivables, and improve collection effectiveness.Oracle Revenue Accounting Gives an organization timely and accurate revenue andflexible commissions reporting.Oracle Sales Analysis: Allows for better forecasting, planning. and reporting of salesinformation.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. Allother modules provide information to it. If you implement Oracle Financials, you shouldswitch your current GL system first.GL is relatively easy to implement. You should go livewith it first to give your implementation team a chance to be familiar with OracleFinancials.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 theirrelationships to be defined within a single installation of Oracle Applications. This keepseach operating units 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 thefield, 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 anassigned name and a set of valid values. Oracle Applications uses flexfields to captureinformation about your organization. There are two types of flexfields: key flexfields anddescriptive flexfields. © IT Engineering Portal : www.itportal.in 248
  • 249. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.INExplain 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. ITEMSWhat is an Alert?An alert is a modal window that displays a message notifies the operator of someapplication conditionWhat are the built-in routines is available in forms 4.0 to create and manipulatea parameter list?Add_parameterCreate_Parameter_listDelete_parameterDestroy_parameter_listGet_parameter_attrGet_parameter_listset_parameter_attrWhat is a record Group?A record group is an internal oracle forms data structure that has a similar column/rowframe work to a database tableWhat is a Navigable item?A navigable item is one that operators can navigate to with the keyboard during defaultnavigation, or that Oracle forms can navigate to by executing a navigational built-inprocedure.What is a library in Forms 4.0?A library is a collection of Pl/SQL program units, including user named procedures,functions & packagesHow image_items can be populate to field in forms 4.0?A fetch from a long raw database column PL/Sql assignment to executing theread_image_file built_in procedure to get an image from the file system.What is the content view and stacked view?A content view is the "Base" view that occupies the entire content pane of the window inwhich it is displayed. A stacked view differs from a content canvas view in that it is notthe base view for the window to which it is assignedWhat is a Check Box?A Check Box is a two state control that indicates whether a certain condition or value ison or off, true or false. The display state of a check box is always either "checked" or"unchecked". © IT Engineering Portal : www.itportal.in 249
  • 250. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.INWhat 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 seeand interact with as they run your form. At run-time, operators can see only those itemsthat have been assigned to a specific canvas. Each canvas, in term, must be displayed ina specific window.Explain the following file extension related to library?.pll,.lib,.pldThe library pll files is a portable design file comparable to an fmb form fileThe library lib file is a plat form specific, generated library file comparable to a fmx formfileThe pld file is Txt format file and can be used for source controlling your library filesParameterExplain the usage of WHERE CURRENT OF clause in cursors ?WHERE CURRENT OF clause in an UPDATE,DELETE statement refers to the latest rowfetched from a cursor. Database TriggersName the tables where characteristics of Package, procedure and functions arestored ?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 ImplicitCursors for queries. User defined cursors are called Explicit Cursors. They can bedeclared and used.What are two parts of package ?The two parts of package are PACKAGE SPECIFICATION & PACKAGE BODY. PackageSpecification contains declarations that are global to the packages and local to theschema. Package Body contains actual procedures and local declaration of theprocedures 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 onlyavailable.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 certainrows are selected from a table. A list of defined policies can be obtained fromDBA_AUDIT_POLICIES. Audit records are stored in DBA_FGA_AUDIT_TRAIL. Look at thisexample:o Add policy on table with autiting condition... © IT Engineering Portal : www.itportal.in 250
  • 251. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.INexecute 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 auditingselect * from EMP where c1 = 09; -- No auditingo 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 PragmaEXECPTION_INIT ? Explain the usage ?The PRAGMA EXECPTION_INIT tells the complier to associate an exception with anoracle error. To get an error message of a specific oracle error. e.g. PRAGMAEXCEPTION_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 usersonly have access to data that pertains to them. Using this option, one could even storemultiple companies data within the same schema, without them knowing about it. VPDconfiguration is done via the DBMS_RLS (Row Level Security) package. Select fromSYS.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 toissue 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 (VirtualPrivate Database) feature of Oracle8i to implement row level security. Access to rows arerestricted according to a users security sensitivity tag or label. Oracle Label Security isconfigured, controlled and managed from the Policy Manager, an Enterprise Manager-based GUI utility.Give the structure of the procedure ?PROCEDURE name (parameter list.....)islocal variable declarationsBEGINExecutable statements.Exception.exception handlersend;What is OEM (Oracle Enterprise Manager)? (for DBA)OEM is a set of systems management tools provided by Oracle Corporation for managingthe Oracle environment. It provides tools to monitor the Oracle environment and © IT Engineering Portal : www.itportal.in 251
  • 252. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.INautomate tasks (both one-time and repetitive in nature) to take database administrationa step closer to "Lights Out" management.Question What is PL/SQL ?PL/SQL is a procedural language that has both interactive SQL and proceduralprogramming 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 theintelligent agents. The OEM Console connects to the management server to monitor andconfigure the Oracle enterprise.. Console: This is a graphical interface from where one can schedule jobs, events, andmonitor the database. The console can be opened from a Windows workstation, UnixXTerm (oemapp command) or Web browser session (oem_webstage).. Intelligent Agent (OIA): The OIA runs on the target database and takes care of theexecution of jobs and events scheduled through the Console.What happens if a procedure that updates a column of table X is called in adatabase trigger of the same table ?Mutation of table occurs.Is it possible to use Transaction control Statements such a ROLLBACK orCOMMIT in Database Trigger ? Why ?It is not possible. As triggers are defined for each table, if you use COMMIT of ROLLBACKin a trigger, it affects logical transaction processing.How many types of database triggers can be specified on a table ? What are they?Insert Update DeleteBefore 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 thestatement.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. © IT Engineering Portal : www.itportal.in 252
  • 253. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.INii. done using Integarity Constraints.?I & ii.Give the structure of the function ?FUNCTION name (argument list .....) Return datatype islocal variable declarationsBeginexecutable statementsExceptionexecution handlersEnd;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 statementcalculate_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 userdefined. Some of Predefined exceptions are.CURSOR_ALREADY_OPENDUP_VAL_ON_INDEXNO_DATA_FOUNDTOO_MANY_ROWSINVALID_CURSORINVALID_NUMBERLOGON_DENIEDNOT_LOGGED_ONPROGRAM-ERRORSTORAGE_ERRORTIMEOUT_ON_RESOURCEVALUE_ERRORZERO_DIVIDEOTHERS.What are the PL/SQL Statements used in cursor processing ?DECLARE CURSOR name, OPEN cursor name, FETCH cursor name INTO or Recordtypes, CLOSE cursor name.What are the components of a PL/SQL Block ?Declarative part, Executable part and Exception part.Datatypes PL/SQL © IT Engineering Portal : www.itportal.in 253
  • 254. July 7, 2011 IT ENGG PORTAL - WWW.ITPORTAL.INWhat is a database trigger ? Name some usages of database trigger ?Database trigger is stored PL/SQL program unit associated with a specific databasetable. Usages are Audit data modifications, Log events transparently, Enforce complexbusiness rules Derive column values automatically, Implement complex securityauthorizations. Maintain replicate tables.What is a cursor ? Why Cursor is required ?Cursor is a named private SQL area from where information can be accessed. Cursorsare 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, fetchesrows of values from active set into fields in the record and closes when all the recordshave been processed.e.g.. FOR emp_rec IN C1 LOOPsalary_total := salary_total +emp_rec sal;END LOOP;What will happen after commit statement ?Cursor C1 isSelect empno,ename from emp;Beginopen C1; loopFetch C1 intoeno.ename;Exit WhenC1 %notfound;-----commit;end loop;end;The cursor having query as SELECT .... FOR UPDATE gets closed afterCOMMIT/ROLLBACK.The cursor having query as SELECT.... does not get closed e