269
C Interview Questions | Frequently Asked Questions (FAQs) 1.What is polymorphism? 'Polymorphism' is an object oriented term. Polymorphism may be defined as the ability of related objects to respond to the same message with different, but appropriate actions. In other words, polymorphism means taking more than one form. Polymorphism leads to two important aspects in Object Oriented terminology - Function Overloading and Function Overriding. Overloading is the practice of supplying more than one definition for a given function name in the same scope. The compiler is left to pick the appropriate version of the function or operator based on the arguments with which it is called. Overriding refers to the modifications made in the sub class to the inherited methods from the base class to change their behaviour. 2.What is operator overloading? When an operator is overloaded, it takes on an additional meaning relative to a certain class. But it can still retain all of its old meanings. Examples: 1) The operators >> and << may be used for I/O operations because in the <iostream> header, they

C Questions

Embed Size (px)

DESCRIPTION

. Base class has some virtual method and derived class has a method with the same name. If we initialize the base class pointer with derived object,. calling of that virtual method will result in which method being called?

Citation preview

Page 1: C Questions

C Interview Questions | Frequently Asked Questions (FAQs)

1.What is polymorphism?

'Polymorphism' is an object oriented term. Polymorphism may be defined as the ability of related objects to respond to the same message with different, but appropriate actions. In other words, polymorphism means taking more than one form. Polymorphism leads to two important aspects in Object Oriented terminology - Function Overloading and Function Overriding.

Overloading is the practice of supplying more than one definition for a given function name in the same scope. The compiler is left to pick the appropriate version of the function or operator based on the arguments with which it is called. Overriding refers to the modifications made in the sub class to the inherited methods from the base class to change their behaviour.

2.What is operator overloading?

When an operator is overloaded, it takes on an additional meaning relative to a certain class. But it can still retain all of its old meanings.Examples:

1) The operators >> and << may be used for I/O operations because in the <iostream> header, they are overloaded.2) In a stack class it is possible to overload the + operator so that it appends the contents of one stack to the contents of another. But the + operator still retains its original meaning relative to other types of data.3.Declare a void pointer.void *malloc(size_t number_of_bytes);malloc is just the library function called to allocated some memory and of course a void pointer will be returned , but it is the declaration of a void pointer.4.Type-define a function pointer which takes a int and float as parameter and returns a float *.

Page 2: C Questions

the pointer to function can be type defined as:typedef float*(*pf)(int a, float b) tagPF; 5.What does the following C statement do? while(*c++ = *d++); assuming c and d are pointers to characters. The loop will be executed until d reaches a null character 6. How do you call a C module within a C++ module. extern "C" {#include <sys/types.h>#include <unistd.h>#include <sys/wait.h>#include <sys/stat.h>#include <fcntl.h>#include <whatever.h>......};

7. What are Templates

C++ Templates allow u to generate families of functions or classes that can operate on a variety of different data types, freeing you from the need to create a separate function or class for each type. Using templates, u have the convenience of writing a single generic function or class definition, which the compiler automatically translates into a specific version of the function or class, for each of the different data types that your program actually uses. Many data structures and algorithms can be defined independently of the type of data they work with. You can increase the amount of shared code by separating data-dependent portions from data-independent portions, and templates were introduced to help you do that.

8. What is the difference between run time binding and compile time binding?

Dynamic Binding : The address of the functions are determined at runtime rather than @ compile time. This is also known as "Late Binding".

Static Binding :The address of the functions are determined at compile time rather than @ run time. This is also known as "Early Binding"

Page 3: C Questions

9. What is Difference Between C/C++

C does not have a class/object concept.C++ provides data abstraction, data encapsulation, Inheritance and Polymorphism.C++ supports all C syntax.In C passing value to a function is "Call by Value" whereas in C++ its "Call by Reference"File extention is .c in C while .cpp in C++.(C++ compiler compiles the files with .c extention but C compiler can not!)In C structures can not have contain functions declarations. In C++ structures are like classes, so declaring functions is legal and allowed.C++ can have inline/virtual functions for the classes. c++ is C with Classes hence C++ while in c the closest u can get to an User defined data type is struct and union

10. What will be the output of the following code?

void main ()

{ int i = 0 , a[3] ;

a[i] = i++;

printf (“%d",a[i]) ;

} The output for the above code would be a garbage value. In the statement a[i] = i++; the value of the variable i would get assigned first to a[i] i.e. a[0] and then the value of i would get incremented by 1. Since a[i] i.e. a[1] has not been initialized, a[i] will have a garbage value.

11. Why doesn't the following code give the desired result?

int x = 3000, y = 2000 ;long int z = x * y ; Here the multiplication is carried out between two ints x and y, and the result that would overflow would be truncated before being assigned to the variable z of type long int. However, to get the correct

Page 4: C Questions

output, we should use an explicit cast to force long arithmetic as shown below:long int z = ( long int ) x * y ; Note that ( long int )( x * y ) would not give the desired effect.

12. Why doesn't the following statement work?

char str[ ] = "Hello" ;strcat ( str, '!' ) ; The string function strcat( ) concatenates strings and not a character. The basic difference between a string and a character is that a string is a collection of characters, represented by an array of characters whereas a character is a single character. To make the above statement work writes the statement as shown below:strcat ( str, "!" ) ;

13. How do I know how many elements an array can hold?

The amount of memory an array can consume depends on the data type of an array. In DOS environment, the amount of memory an array can consume depends on the current memory model (i.e. Tiny, Small, Large, Huge, etc.). In general an array cannot consume more than 64 kb. Consider following program, which shows the maximum number of elements an array of type int, float and char can have in case of Small memory model.

main( ){

int i[32767] ;

float f[16383] ;

char s[65535] ;

}

14. How do I write code that reads data at memory location specified by segment and offset?

Use peekb( ) function. This function returns byte(s) read from specific

Page 5: C Questions

segment and offset locations in memory. The following program illustrates use of this function. In this program from VDU memory we have read characters and its attributes of the first row. The information stored in file is then further read and displayed using peek( ) function. #include <stdio.h>

#include <dos.h>main( )

{

char far *scr = 0xB8000000 ;

FILE *fp ;

int offset ;

char ch ;

if ( ( fp = fopen ( "scr.dat", "wb" ) ) == NULL )

{

printf ( "\nUnable to open file" ) ;

exit( ) ;

}

// reads and writes to file

for ( offset = 0 ; offset < 160 ; offset++ )

fprintf ( fp, "%c", peekb ( scr, offset ) ) ;

fclose ( fp ) ;

if ( ( fp = fopen ( "scr.dat", "rb" ) ) == NULL )

{

Page 6: C Questions

printf ( "\nUnable to open file" ) ;

exit( ) ;

}

// reads and writes to file

for ( offset = 0 ; offset < 160 ; offset++ )

{

fscanf ( fp, "%c", &ch ) ;

printf ( "%c", ch ) ;

}

fclose ( fp ) ;

}

What is the difference between #include <file> and #include “file”?

When writing your C program, you can include files in two ways. The first way is to surround the file youwant to include with the angled brackets < and >. This method of inclusion tells the preprocessor to look for the file in the predefined default location. This predefined default location is often an INCLUDE environment variable that denotes the path to your include files. For instance, given the INCLUDE variable

INCLUDE=C:\COMPILER\INCLUDE;S:\SOURCE\HEADERS;

using the #include <file> version of file inclusion, the compiler first checks the C:\COMPILER\INCLUDEdirectory for the specified file. If the file is not found there, the compiler then checks theS:\SOURCE\HEADERS directory. If the file is still not found, the preprocessor checks the current directory.

Page 7: C Questions

The second way to include files is to surround the file you want to include with double quotation marks. This method of inclusion tells the preprocessor to look for the file in the current directory first, then look for it in the predefined locations you have set up. Using the #include “file” version of file inclusion and applying it to the preceding example, the preprocessor first checks the current directory for the specified file. If the file is not found in the current directory, the C:COMPILERINCLUDE directory is searched. If the file is still not found, the preprocessor checks the S:SOURCEHEADERS directory.The #include <file> method of file inclusion is often used to include standard headers such as stdio.h orstdlib.h. This is because these headers are rarely (if ever) modified, and they should always be read from your compiler’s standard include file directory.

The #include “file” method of file inclusion is often used to include nonstandard header files that you have created for use in your program. This is because these headers are often modified in the current directory, and you will want the preprocessor to use your newly modified version of the header rather than the older, unmodified version.

What is the benefit of using an enum rather than a #define constant?

The use of an enumeration constant (enum) has many advantages over using the traditional symbolic constant style of #define. These advantages include a lower maintenance requirement, improved program readability, and better debugging capability.

1) The first advantage is that enumerated constants are generated automatically by the compiler. Conversely, symbolic constants must be manually assigned values by the programmer.

For instance, if you had an enumerated constant type for error codes that could occur in your program, your enum definition could look something like this:

enum Error_Code{OUT_OF_MEMORY,INSUFFICIENT_DISK_SPACE,

Page 8: C Questions

LOGIC_ERROR,FILE_NOT_FOUND};

In the preceding example, OUT_OF_MEMORY is automatically assigned the value of 0 (zero) by the compiler because it appears first in the definition. The compiler then continues to automatically assign numbers to the enumerated constants, making INSUFFICIENT_DISK_SPACE equal to 1, LOGIC_ERROR equal to 2, and FILE_NOT_FOUND equal to 3, so on.

If you were to approach the same example by using symbolic constants, your code would look something like this:

#define OUT_OF_MEMORY 0#define INSUFFICIENT_DISK_SPACE 1#define LOGIC_ERROR 2#define FILE_NOT_FOUND 3values by the programmer. Each of the two methods arrives at the same result: four constants assigned numeric values to represent error codes. Consider the maintenance required, however, if you were to add two constants to represent the error codes DRIVE_NOT_READY and CORRUPT_FILE. Using the enumeration constant method, you simply would put these two constants anywhere in the enum definition. The compiler would generate two unique values for these constants. Using the symbolic constant method, you would have to manually assign two new numbers to these constants. Additionally, you would want to ensure that the numbers you assign to these constants are unique.

2) Another advantage of using the enumeration constant method is that your programs are more readable and thus can be understood better by others who might have to update your program later.

3) A third advantage to using enumeration constants is that some symbolic debuggers can print the value of an enumeration constant. Conversely, most symbolic debuggers cannot print the value of a symbolic constant. This can be an enormous help in debugging your program, because if your program is stopped at a line that uses an enum, you can simply inspect that constant and instantly know its

Page 9: C Questions

value. On the other hand, because most debuggers cannot print #define values, you would most likely have to search for that value by manually looking it up in a header file.

How can I open a file so that other programs can update it at the same time?

Your C compiler library contains a low-level file function called sopen() that can be used to open a file in shared mode. Beginning with DOS 3.0, files could be opened in shared mode by loading a special program named SHARE.EXE. Shared mode, as the name implies, allows a file to be shared with other programs as well as your own.

Using this function, you can allow other programs that are running to update the same file you are updating.The sopen() function takes four parameters: a pointer to the filename you want to open, the operationalmode you want to open the file in, the file sharing mode to use, and, if you are creating a file, the mode to create the file in. The second parameter of the sopen() function, usually referred to as the “operation flag”parameter, can have the following values assigned to it:

Constant Description O_APPEND Appends all writes to the end of the file

O_BINARY Opens the file in binary (untranslated) modeO_CREAT If the file does not exist, it is createdO_EXCL If the O_CREAT flag is used and the file exists, returns an errorO_RDONLY Opens the file in read-only modeO_RDWR Opens the file for reading and writingO_TEXT Opens the file in text (translated) modeO_TRUNC Opens an existing file and writes over its contentsO_WRONLY Opens the file in write-only mode

The third parameter of the sopen() function, usually referred to as the “sharing flag,” can have the following values assigned to it:

Page 10: C Questions

Constant DescriptionSH_COMPAT No other program can access the fileSH_DENYRW No other program can read from or write to the fileSH_DENYWR No other program can write to the fileSH_DENYRD No other program can read from the fileSH_DENYNO Any program can read from or write to the file

If the sopen() function is successful, it returns a non-negative number that is the file’s handle. If an error occurs, –1 is returned, and the global variable errno is set to one of the following values:

Constant DescriptionENOENT File or path not foundEMFILE No more file handles are availableEACCES Permission denied to access fileEINVACC Invalid access codeConstant Description

What is hashing?

To hash means to grind up, and that’s essentially what hashing is all about. The heart of a hashing algorithm is a hash function that takes your nice, neat data and grinds it into some random-looking integer.

The idea behind hashing is that some data either has no inherent ordering (such as images) or is expensive to compare (such as images). If the data has no inherent ordering, you can’t perform comparison searches.

If the data is expensive to compare, the number of comparisons used even by a binary search might be too many. So instead of looking at the data themselves, you’ll condense (hash) the data to an integer (its hash value) and keep all the data with the same hash value in the same place. This task is carried out by using the hash value as an index into an array.

To search for an item, you simply hash it and look at all the data whose hash values match that of the data you’re looking for. This technique greatly lessens the number of items you have to look at. If the parameters are set up with care and enough storage is available

Page 11: C Questions

for the hash table, the number of comparisons needed to find an item can be made arbitrarily close to one.

One aspect that affects the efficiency of a hashing implementation is the hash function itself. It should ideally distribute data randomly throughout the entire hash table, to reduce the likelihood of collisions. Collisions occur when two different keys have the same hash value. There are two ways to resolve this problem. In “open addressing,” the collision is resolved by the choosing of another position in the hash table for the element inserted later. When the hash table is searched, if the entry is not found at itshashed position in the table, the search continues checking until either the element is found or an empty position in the table is found

The second method of resolving a hash collision is called “chaining.” In this method, a “bucket” or linked list holds all the elements whose keys hash to the same value.

When the hash table is searched, the list must be searched linearly.

What is the quickest sorting method to use?

The answer depends on what you mean by quickest. For most sorting problems, it just doesn’t matter how quick the sort is because it is done infrequently or other operations take significantly more time anyway. Even in cases in which sorting speed is of the essence, there is no one answer. It depends on not only the size and nature of the data, but also the likely order. No algorithm is best in all cases.

There are three sorting methods in this author’s “toolbox” that are all very fast and that are useful in different situations. Those methods are quick sort, merge sort, and radix sort.

The Quick SortThe quick sort algorithm is of the “divide and conquer” type. That means it works by reducing a sorting problem into several easier sorting problems and solving each of them. A “dividing” value is chosen from the input data, and the data is partitioned into three sets: elements that belong before the dividing value, the value itself, and elements that come after the dividing value. The partitioning is performed by exchanging elements that are in the first set but belong

Page 12: C Questions

in the third with elements that are in the third set but belong in the first Elements that are equal to the dividing element can be put in any of the three sets—the algorithm will still work properly.

The Merge SortThe merge sort is a “divide and conquer” sort as well. It works by considering the data to be sorted as a sequence of already-sorted lists (in the worst case, each list is one element long). Adjacent sorted lists are merged into larger sorted lists until there is a single sorted list containing all the elements. The merge sort is good at sorting lists and other data structures that are not in arrays, and it can be used to sort things that don’t fit into memory. It also can be implemented as a stable sort.

The Radix SortThe radix sort takes a list of integers and puts each element on a smaller list, depending on the value of its least significant byte. Then the small lists are concatenated, and the process is repeated for each more significant byte until the list is sorted. The radix sort is simpler to implement on fixed-length data such as ints.

when should the volatile modifier be used?

The volatile modifier is a directive to the compiler’s optimizer that operations involving this variable should not be optimized in certain ways. There are two special cases in which use of the volatile modifier is desirable. The first case involves memory-mapped hardware (a device such as a graphics adaptor that appears to the computer’s hardware as if it were part of the computer’s memory), and the second involves shared memory (memory used by two or more programs running simultaneously).

Most computers have a set of registers that can be accessed faster than the computer’s main memory. A good compiler will perform a kind of optimization called “redundant load and store removal.” The compiler looks for places in the code where it can either remove an instruction to load data from memory because the value is already in a register, or remove an instruction to store data to memory because the value can stay in a register until it is changed again anyway.

Page 13: C Questions

If a variable is a pointer to something other than normal memory, such as memory-mapped ports on a peripheral, redundant load and store optimizations might be detrimental. For instance, here’s a piece of code that might be used to time some operation:

time_t time_addition(volatile const struct timer *t, int a){int n;int x;time_t then;x = 0;then = t->value;for (n = 0; n < 1000; n++){x = x + a;}return t->value - then;}

In this code, the variable t->value is actually a hardware counter that is being incremented as time passes. The function adds the value of a to x 1000 times, and it returns the amount the timer was incremented by while the 1000 additions were being performed. Without the volatile modifier, a clever optimizer might assume that the value of t does not change during the execution of the function, because there is no statement that explicitly changes it. In that case, there’s no need to read it from memory a second time and subtract it, because the answer will always be 0. The compiler might therefore “optimize” the function by making it always return 0.

If a variable points to data in shared memory, you also don’t want the compiler to perform redundant load and store optimizations. Shared memory is normally used to enable two programs to communicate with each other by having one program store data in the shared portion of memory and the other program read the same portion of memory. If the compiler optimizes away a load or store of shared memory, communication between the two programs will be affected.

When should the register modifier be used? Does it really help?

Page 14: C Questions

The register modifier hints to the compiler that the variable will be heavily used and should be kept in the CPU’s registers, if possible, so that it can be accessed faster.

There are several restrictions on the use of the register modifier.

First, the variable must be of a type that can be held in the CPU’s register. This usually means a single value of a size less than or equal to the size of an integer. Some machines have registers that can hold floating-point numbers as well.

Second, because the variable might not be stored in memory, its address cannot be taken with the unary & operator. An attempt to do so is flagged as an error by the compiler. Some additional rules affect how useful the register modifier is. Because the number of registers is limited, and because some registers can hold only certain types of data (such as pointers or floating-point numbers), the number and types of register modifiers that will actually have any effect are dependent on what machine theprogram will run on. Any additional register modifiers are silently ignored by the compiler.

Also, in some cases, it might actually be slower to keep a variable in a register because that register then becomes unavailable for other purposes or because the variable isn’t used enough to justify the overhead of loading and storing it.

So when should the register modifier be used? The answer is never, with most modern compilers. Early C compilers did not keep any variables in registers unless directed to do so, and the register modifier was a valuable addition to the language. C compiler design has advanced to the point, however, where the compiler will usually make better decisions than the programmer about which variables should be stored in registers.

In fact, many compilers actually ignore the register modifier, which is perfectly legal, because it is only a hint and not a directive.

What is page thrashing?

Page 15: C Questions

Some operating systems (such as UNIX or Windows in enhanced mode) use virtual memory. Virtualmemory is a technique for making a machine behave as if it had more memory than it really has, by using disk space to simulate RAM (random-access memory). In the 80386 and higher Intel CPU chips, and in most other modern microprocessors (such as the Motorola 68030, Sparc, and Power PC), exists a piece of hardware called the Memory Management Unit, or MMU.

The MMU treats memory as if it were composed of a series of “pages.” A page of memory is a block of contiguous bytes of a certain size, usually 4096 or 8192 bytes. The operating system sets up and maintains a table for each running program called the Process Memory Map, or PMM. This is a table of all the pages of memory that program can access and where each is really located.

Every time your program accesses any portion of memory, the address (called a “virtual address”) is processed by the MMU. The MMU looks in the PMM to find out where the memory is really located (called the “physical address”). The physical address can be any location in memory or on disk that the operating system has assigned for it. If the location the program wants to access is on disk, the page containing it must be read from disk into memory, and the PMM must be updated to reflect this action (this is called a “page fault”).

Because accessing the disk is so much slower than accessing RAM, the operating system tries to keep as much of the virtual memory as possible in RAM. If you’re running a large enough program (or several small programs at once), there might not be enough RAM to hold all the memory used by the programs, so some of it must be moved out of RAM and onto disk (this action is called “paging out”). The operating system tries to guess which areas of memory aren’t likely to be used for a while (usually based on how the memory has been used in the past). If it guesses wrong, or if your programs are accessing lots of memory in lots of places, many page faults will occur in order to read in the pages that were paged out. Because all of RAM is being used, for each page read in to be accessed, another page must be paged out. This can lead to more page faults, because now a different page of memory has been moved to disk.

Page 16: C Questions

The problem of many page faults occurring in a short time, called “page thrashing,” can drastically cut the performance of a system. Programs that frequently access many widely separated locations in memory are more likely to cause page thrashing on a system. So is running many small programs that all continue to run even when you are not actively using them. To reduce page thrashing, you can run fewer programs simultaneously. Or you can try changing the way a large program works to maximize the capability of the operating system to guess which pages won’t be needed. You can achieve this effect by caching values or changing lookup algorithms in large data structures, or sometimes by changing to a memory allocation library which provides an implementation of malloc() that allocates memory more efficiently. Finally, you might consider adding more RAM to the system to reduce the need to page out.

How can you determine the size of an allocated portion of memory?

You can’t, really. free() can , but there’s no way for your program to know the trick free() uses. Even if you disassemble the library and discover the trick, there’s no guarantee the trick won’t change with the next release of the compiler.

Can static variables be declared in a header file?

You can’t declare a static variable without defining it as well (this is because the storage class modifiersstatic and extern are mutually exclusive). A static variable can be defined in a header file, but this would cause each source file that included the header file to have its own private copy of the variable, which is probably not what was intended.

How do you override a defined macro?

You can use the #undef preprocessor directive to undefine (override) a previously defined macro.

How can you check to see whether a symbol is defined?

Page 17: C Questions

You can use the #ifdef and #ifndef preprocessor directives to check whether a symbol has been defined(#ifdef) or whether it has not been defined (#ifndef).

Can you define which header file to include at compile time?

Yes. This can be done by using the #if, #else, and #endif preprocessor directives. For example, certaincompilers use different names for header files. One such case is between Borland C++, which uses the header file alloc.h, and Microsoft C++, which uses the header file malloc.h. Both of these headers serve the same purpose, and each contains roughly the same definitions. If, however, you are writing a program that is to support Borland C++ and Microsoft C++, you must define which header to include at compile time. The following example shows how this can be done:

#ifdef _ _BORLANDC_ _#include <alloc.h>#else#include <malloc.h>#endif

Can a variable be both const and volatile?

Yes. The const modifier means that this code cannot change the value of the variable, but that does not mean that the value cannot be changed by means outside this code. For instance, in the example inFAQ 8, the timer structure was accessed through a volatile const pointer. The function itself did not change the value of the timer, so it was declared const. However, the value was changed by hardware on the computer, so it was declared volatile. If a variable is both const and volatile, the two modifiers can appear in either order.

Can include files be nested?

Yes. Include files can be nested any number of times. As long as you use precautionary measures , you can avoid including the same file twice. In the past, nesting header files was seen as bad programming practice, because it complicates the dependency tracking function of the MAKE program and thus slows down compilation. Many of

Page 18: C Questions

today’s popular compilers make up for this difficulty by implementing a concept called precompiled headers, in which all headers and associated dependencies are stored ina precompiled state.

Many programmers like to create a custom header file that has #include statements for every header needed for each module. This is perfectly acceptable and can help avoid potential problems relating to #include files, such as accidentally omitting an #include file in a module.

Write the equivalent expression for x%8?

x&7

When does the compiler not implicitly generate the address of the first element of an array?

Whenever an array name appears in an expression such as

Ø array as an operand of the sizeof operator

Ø array as an operand of & operator

Ø array as a string literal initializer for a character array

Then the compiler does not implicitly generate the address of the address of the first element of an array.

What is the benefit of using #define to declare a constant?

Using the #define method of declaring a constant enables you to declare a constant in one place and use it throughout your program. This helps make your programs more maintainable, because you need to maintain only the #define statement and not several instances of individual constants throughout your program.

For instance, if your program used the value of pi (approximately 3.14159) several times, you might want to declare a constant for pi as follows:

Page 19: C Questions

#define PI 3.14159

Using the #define method of declaring a constant is probably the most familiar way of declaring constants to traditional C programmers. Besides being the most common method of declaring constants, it also takes up the least memory. Constants defined in this manner are simply placed directly into your source code, with no variable space allocated in memory. Unfortunately, this is one reason why most debuggers cannot inspect constants created using the #define method.

How can I search for data in a linked list?

Unfortunately, the only way to search a linked list is with a linear search, because the only way a linked list’s members can be accessed is sequentially. Sometimes it is quicker to take the data from a linked list and store it in a different data structure so that searches can be more efficient.

Why should we assign NULL to the elements (pointer) after freeing them?

This is paranoia based on long experience. After a pointer has been freed, you can no longer use the pointed-to data. The pointer is said to “dangle”; it doesn’t point at anything useful. If you “NULL out” or “zero out” a pointer immediately after freeing it, your program can no longer get in trouble by using that pointer. True, you might go indirect on the null pointer instead, but that’s something your debugger might be able to help you with immediately. Also, there still might be copies of the pointer that referto the memory that has been deallocated; that’s the nature of C. Zeroing out pointers after freeing them won’t solve all problems;

What is a “null pointer assignment” error? What are bus errors, memory faults, and core dumps?

These are all serious errors, symptoms of a wild pointer or subscript.

Null pointer assignment is a message you might get when an MS-DOS program finishes executing. Somesuch programs can arrange for a small amount of memory to be

Page 20: C Questions

available “where the NULL pointer points to” (so to speak). If the program tries to write to that area, it will overwrite the data put there by the compiler.

When the program is done, code generated by the compiler examines that area. If that data has been changed, the compiler-generated code complains with null pointer assignment.

This message carries only enough information to get you worried. There’s no way to tell, just from a null pointer assignment message, what part of your program is responsible for the error. Some debuggers, and some compilers, can give you more help in finding the problem.

Bus error: core dumped and Memory fault: core dumped are messages you might see from a program running under UNIX. They’re more programmer friendly. Both mean that a pointer or an array subscript was wildly out of bounds. You can get these messages on a read or on a write. They aren’t restricted to null pointer problems.

The core dumped part of the message is telling you about a file, called core, that has just been written in your current directory. This is a dump of everything on the stack and in the heap at the time the program was running. With the help of a debugger, you can use the core dump to find where the bad pointer was used.

That might not tell you why the pointer was bad, but it’s a step in the right direction. If you don’t have write permission in the current directory, you won’t get a core file, or the core dumped message.

When should a type cast be used?

There are two situations in which to use a type cast. The first use is to change the type of an operand to an arithmetic operation so that the operation will be performed properly.

The second case is to cast pointer types to and from void * in order to interface with functions that expect or return void pointers. For example, the following line type casts the return value of the call to malloc() to be a pointer to a foo structure.

Page 21: C Questions

struct foo *p = (struct foo *) malloc(sizeof(struct foo));

What is a null pointer?

There are times when it’s necessary to have a pointer that doesn’t point to anything. The macro NULL, defined in <stddef.h>, has a value that’s guaranteed to be different from any valid pointer. NULL is a literal zero, possibly cast to void* or char*. Some people, notably C++ programmers, prefer to use 0 rather than NULL.

The null pointer is used in three ways:

1) To stop indirection in a recursive data structure

2) As an error value

3) As a sentinel value

1. Difference between directcast and ctype.

DirectCast requires the run-time type of an object variable to be the same as the specified type.The run-time performance of Direct Cast is better than that of CType, if the specified type and the run-time type of the expression are the same.Ctype works fine if there is a valid conversion defined between the expression and the type.

2. An example of a ctype and direct cast.

3. ctype(123.34,integer) - should it throw an error? Why or why not?

the ctype(123.34,integer) will work fine no errors It would work fine. As the runtime type of 123.34 would be double, and Double can be converted to Integer.

4. directcast(123.34,integer) - should it throw an error? Why or why not?

It would throw an Invalid Cast exception as the runtime type of 123.34 (double) doesn't match with Integer.

5. Difference between a sub and a function.

Page 22: C Questions

-A Sub Procedure is a method will not return a value -A sub procedure will be defined with a “Sub” keyword Sub ShowName(ByVal my Name As String) Console.WriteLine(”My name is: ” & my Name) End Sub

-A function is a method that will return value's).-A function will be defined with a “Function” keyword

Function FindSum(ByVal num1 As Integer, By Val num2 As Integer) As IntegerDim sum As Integer = num1 + num2Return sumEnd Function

6. Explain manifest & metadata.

Manifest is metadata about assemblies. Metadata is machine-readable information about a resource, or “”data about data.” In .NET, metadata includes type definitions, version information, external assembly references, and other standardized information.

7. Scope of public/private/friend/protected/protected friend.

Visual Basic/Visual C#

Public/public All members in all classes and projects.

Private/private Members of the current class only.

Friend/internal All members in the current project.

Protected/protected All members in the current class and in classes derived from this member’s class. Can be used only in member definitions, not for class or module definitions.

Protected Friend/protected internal All members in the current project and all members in classes derived from this member’s class. Can be used only in member definitions, not for class or module definitions.

8. Different kinds of methods.

Page 23: C Questions

9. Difference between imperative and interrogative code.

There are imperative and interrogative functions and I think they are talking about that. Imperative functions are the one which return a value while the interrogative functions do not return a value.

10. Difference between value and reference type.

Value type - bool, byte, chat, decimal, double, enum , float, int, long, sbyte, short, strut, uint, ulong, ushort Value types are stored in the StackReference type - class, delegate, interface, object, stringReference types are stored in the Heap

11. What are the two kinds of properties.

Two types of properties in .Net: Get & Set

12. What is the raise event used for?

Raise events are well explained herer: http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vblr7/html/vastmRaiseEvent.asp

13. Explain constructor.

Constructor is a method in the class which has the same name as the class (in VB.Net its New()). It initialises the member attributes whenever an instance of the class is created.

14. What is a resource? Provide an example from your recent project.

15. What is a system lock?

16. Describe ways of cleaning up objects.

There is a perfect tool provide by .net frameworks calles Garbage collector, where by mean of GC we can clean up the object and reclaim the memory.The namespace used is System.GC

Page 24: C Questions

17. Where does the dispose method lie and how can it be used to clean up resources?

18. How can you clean up objects holding resources from within the code?

Call the dispose method from code for clean up of objects

19.Which controls do not have events?

Timer control.

20.What is the maximum size of the textbox?

65536.

21.Which property of the textbox cannot be changed at runtime?

Locked Porperty.

22.Which control cannot be placed in MDI?

The controls that do not have events.

What is the difference between a string copy (strcpy) and a memory copy (memcpy)? When should each be used?

The strcpy() function is designed to work exclusively with strings. It copies each byte of the source string to the destination string and stops when the terminating null character () has been moved. On the other hand, the memcpy() function is designed to work with any type of data. Because not all data ends with a null character, you must provide the memcpy() function with the number of bytes you want to copy from the source to the destination.

How can I convert a string to a number?

The standard C library provides several functions for converting strings to numbers of all formats (integers, longs, floats, and so on) and vice versa.

The following functions can be used to convert strings to numbers:

Page 25: C Questions

Function Name Purpose

atof() Converts a string to a double-precision floating-point value.atoi() Converts a string to an integer.atol() Converts a string to a long integer.strtod() Converts a string to a double-precision floating-point value and reports any “leftover” numbers that could not be converted.strtol() Converts a string to a long integer and reports any “leftover” numbers that could not be converted.strtoul() Converts a string to an unsigned long integer and reports any “leftover” numbers that could not be converted.

How can I convert a number to a string?

The standard C library provides several functions for converting numbers of all formats (integers, longs, floats, and so on) to strings and vice versa The following functions can be used to convert integers to strings:

Function Name Purpose

itoa() Converts an integer value to a string.ltoa() Converts a long integer value to a string.ultoa() Converts an unsigned long integer value to a string.

The following functions can be used to convert floating-point values to strings:

Function Name Purpose

ecvt() Converts a double-precision floating-point value to a string without an embedded decimal point.fcvt() Same as ecvt(), but forces the precision to a specified number of digits.gcvt() Converts a double-precision floating-point value to a string with an embedded decimal point.

Is it possible to execute code even after the program exits the main() function?

Page 26: C Questions

The standard C library provides a function named atexit() that can be used to perform “cleanup” operations when your program terminates. You can set up a set of functions you want to perform automatically when your program exits by passing function pointers to the at exit() function.

What is the stack?

The stack is where all the functions’ local (auto) variables are created. The stack also contains some information used to call and return from functions.

A “stack trace” is a list of which functions have been called, based on this information. When you start using a debugger, one of the first things you should learn is how to get a stack trace.

The stack is very inflexible about allocating memory; everything must be deallocated in exactly the reverse order it was allocated in. For implementing function calls, that is all that’s needed. Allocating memory off the stack is extremely efficient. One of the reasons C compilers generate such good code is their heavy use of a simple stack.

There used to be a C function that any programmer could use for allocating memory off the stack. The memory was automatically deallocated when the calling function returned. This was a dangerous function to call; it’s not available anymore.

How do you print an address?

The safest way is to use printf() (or fprintf() or sprintf()) with the %P specification. That prints a void pointer (void*). Different compilers might print a pointer with different formats. Your compiler will pick a format that’s right for your environment.

If you have some other kind of pointer (not a void*) and you want to be very safe, cast the pointer to a void*:

printf( “%Pn”, (void*) buffer );

Can a file other than a .h file be included with #include?

Page 27: C Questions

The preprocessor will include whatever file you specify in your #include statement. Therefore, if you have the line #include <macros.inc>

in your program, the file macros.inc will be included in your precompiled program. It is, however, unusual programming practice to put any file that does not have a .h or .hpp extension in an #include statement.

You should always put a .h extension on any of your C files you are going to include. This method makes it easier for you and others to identify which files are being used for preprocessing purposes. For instance, someone modifying or debugging your program might not know to look at the macros.inc file for macro definitions. That person might try in vain by searching all files with .h extensions and come up empty. If your file had been named macros.h, the search would have included the macros.h file, and the searcher would have been able to see what macros you defined in it.

What is Preprocessor?

The preprocessor is used to modify your program according to the preprocessor directives in your source code. Preprocessor directives (such as #define) give the preprocessor specific instructions on how to modify your source code. The preprocessor reads in all of your include files and the source code you are compiling and creates a preprocessed version of your source code. This preprocessed version has all of its macros and constant symbols replaced by their corresponding code and value assignments. If your source code contains any conditional preprocessor directives (such as #if), the preprocessor evaluates the condition and modifies your source code accordingly.The preprocessor contains many features that are powerful to use, such as creating macros, performing conditional compilation, inserting predefined environment variables into your code, and turning compiler features on and off. For the professional programmer, in-depth knowledge of the features of the preprocessor can be one of the keys to creating fast, efficient programs.

How can you restore a redirected standard stream?

Page 28: C Questions

The preceding example showed how you can redirect a standard stream from within your program. But what if later in your program you wanted to restore the standard stream to its original state? By using the standard C library functions named dup() and fdopen(), you can restore a standard stream such as stdout to its original state.

The dup() function duplicates a file handle. You can use the dup() function to save the file handle corresponding to the stdout standard stream. The fdopen() function opens a stream that has been duplicated with the dup() function.

What is the heap?

The heap is where malloc(), calloc(), and realloc() get memory.

Getting memory from the heap is much slower than getting it from the stack. On the other hand, the heap is much more flexible than the stack. Memory can be allocated at any time and deallocated in any order. Such memory isn’t deallocated automatically; you have to call free().

Recursive data structures are almost always implemented with memory from the heap. Strings often come from there too, especially strings that could be very long at runtime. If you can keep data in a local variable (and allocate it from the stack), your code will run faster than if you put the data on the heap. Sometimes you can use a better algorithm if you use the heap—faster, or more robust, or more flexible. It’s a tradeoff.

If memory is allocated from the heap, it’s available until the program ends. That’s great if you remember to deallocate it when you’re done. If you forget, it’s a problem. A “memory leak” is some allocated memory that’s no longer needed but isn’t deallocated. If you have a memory leak inside a loop, you can use up all the memory on the heap and not be able to get any more. (When that happens, the allocation functions return a null pointer.) In some environments, if a program doesn’t deallocate everything it allocated, memory stays unavailable even after the program ends.

How do you use a pointer to a function?

Page 29: C Questions

The hardest part about using a pointer-to-function is declaring it.Consider an example. You want to create a pointer, pf, that points to the strcmp() function.The strcmp() function is declared in this way:int strcmp(const char *, const char * )

To set up pf to point to the strcmp() function, you want a declaration that looks just like the strcmp() function’s declaration, but that has *pf rather than strcmp:

int (*pf)( const char *, const char * );

After you’ve gotten the declaration of pf, you can #include <string.h> and assign the address of strcmp() to pf: pf = strcmp;

What is the purpose of realloc( )?

The function realloc(ptr,n) uses two arguments.the first argument ptr is a pointer to a block of memory for which the size is to be altered.The second argument n specifies thenew size.The size may be increased or decreased.If n is greater than the old size and if sufficient space is not available subsequent to the old region, the function realloc( )may create a new region and all the old data are moved to the new region.

What is the purpose of main( ) function?

The function main( ) invokes other functions within it.It is the first function to be called when the program starts execution.

Ø It is the starting functionØ It returns an int value to the environment that called the programØ Recursive call is allowed for main( ) also.Ø It is a user-defined functionØ Program execution ends when the closing brace of the function main( ) is reached.Ø It has two arguments 1)argument count and 2) argument vector (represents strings passed).Ø Any user-defined name can also be used as parameters for main( ) instead of argc and argv

Page 30: C Questions

why n++ executes faster than n+1?

The expression n++ requires a single machine instruction such as INR to carry out the increment operation whereas, n+1 requires more instructions to carry out this operation.

What will the preprocessor do for a program?

The C preprocessor is used to modify your program according to the preprocessor directives in your source code. A preprocessor directive is a statement (such as #define) that gives the preprocessor specific instructions on how to modify your source code. The preprocessor is invoked as the first part of your compiler program’s compilation step. It is usually hidden from the programmer because it is run automatically by the compiler.

The preprocessor reads in all of your include files and the source code you are compiling and creates a preprocessed version of your source code. This preprocessed version has all of its macros and constant symbols replaced by their corresponding code and value assignments. If your source code contains any conditional preprocessor directives (such as #if), the preprocessor evaluates the condition and modifies your source code accordingly.

What is the benefit of using const for declaring constants?

The benefit of using the const keyword is that the compiler might be able to make optimizations based on the knowledge that the value of the variable will not change. In addition, the compiler will try to ensure that the values won’t be changed inadvertently.

Of course, the same benefits apply to #defined constants. The reason to use const rather than #define to define a constant is that a const variable can be of any type (such as a struct, which can’t be represented by a #defined constant). Also, because a const variable is a real variable, it has an address that can be used, if needed, and it resides in only one place in memory

What is the easiest sorting method to use?

Page 31: C Questions

The answer is the standard library function qsort(). It’s the easiest sort by far for several reasons:

It is already written.It is already debugged.It has been optimized as much as possible (usually).Void qsort(void *buf, size_t num, size_t size, int (*comp)(const void *ele1, const void *ele2));

How many levels of pointers can you have?

The answer depends on what you mean by “levels of pointers.” If you mean “How many levels of indirection can you have in a single declaration?” the answer is “At least 12.”

int i = 0;int *ip01 = & i;int **ip02 = & ip01;int ***ip03 = & ip02;int ****ip04 = & ip03;int *****ip05 = & ip04;int ******ip06 = & ip05;int *******ip07 = & ip06;int ********ip08 = & ip07;int *********ip09 = & ip08;int **********ip10 = & ip09;int ***********ip11 = & ip10;int ************ip12 = & ip11;************ip12 = 1; /* i = 1 */

The ANSI C standard says all compilers must handle at least 12 levels. Your compiler might support more.

Is it better to use a macro or a function?

The answer depends on the situation you are writing code for. Macros have the distinct advantage of being more efficient (and faster) than functions, because their corresponding code is inserted directly into your source code at the point where the macro is called. There is no overhead involved in using a macro like there is in placing a call to a function. However, macros are generally small and cannot

Page 32: C Questions

handle large, complex coding constructs. A function is more suited for this type of situation. Additionally, macros are expanded inline, which means that the code is replicated for each occurrence of a macro. Your code therefore could be somewhat larger when you use macros than if you were to use functions.

Thus, the choice between using a macro and using a function is one of deciding between the tradeoff of faster program speed versus smaller program size. Generally, you should use macros to replace small, repeatable code sections, and you should use functions for larger coding tasks that might require several lines of code.

What are the standard predefined macros?

The ANSI C standard defines six predefined macros for use in the C language:

Macro Name Purpose

_ _LINE_ _ Inserts the current source code line number in your code._ _FILE_ _ Inserts the current source code filename in your code._ _DATE_ _ Inserts the current date of compilation in your code._ _TIME_ _ Inserts the current time of compilation in your code._ _STDC_ _ Is set to 1 if you are enforcing strict ANSI C conformity._ _cplusplus Is defined if you are compiling a C++ program.

What is a const pointer?

The access modifier keyword const is a promise the programmer makes to the compiler that the value of a variable will not be changed after it is initialized. The compiler will enforce that promise as best it can by not enabling the programmer to write code which modifies a variable that has been declared const.

A “const pointer,” or more correctly, a “pointer to const,” is a pointer which points to data that is const (constant, or unchanging). A pointer to const is declared by putting the word const at the beginning of the pointer declaration. This declares a pointer which points to data that can’t be modified. The pointer itself can be modified. The following example illustrates some legal and illegal uses of a const pointer:

Page 33: C Questions

const char *str = “hello”;char c = *str /* legal */str++; /* legal */*str = ‘a’; /* illegal */str[1] = ‘b’; /* illegal */

What is a pragma?

The #pragma preprocessor directive allows each compiler to implement compiler-specific features that can be turned on and off with the #pragma statement. For instance, your compiler might support a feature called loop optimization. This feature can be invoked as a command-line option or as a #pragma directive.

To implement this option using the #pragma directive, you would put the following line into your code:

#pragma loop_opt(on)

Conversely, you can turn off loop optimization by inserting the following line into your code:

#pragma loop_opt(off)

What is #line used for?

The #line preprocessor directive is used to reset the values of the _ _LINE_ _ and _ _FILE_ _ symbols, respectively. This directive is commonly used in fourth-generation languages that generate C language source files.

What is the difference between text and binary modes?

Streams can be classified into two types: text streams and binary streams. Text streams are interpreted, with a maximum length of 255 characters. With text streams, carriage return/line feed combinations are translated to the newline n character and vice versa. Binary streams are uninterpreted and are treated one byte at a time with no translation of characters. Typically, a text stream would be used for reading and writing standard text files, printing output to the screen or printer, or receiving input from the keyboard.

Page 34: C Questions

A binary text stream would typically be used for reading and writing binary files such as graphics or word processing documents, reading mouse input, or reading and writing to the modem.

How do you determine whether to use a stream function or a low-level function?

Stream functions such as fread() and fwrite() are buffered and are more efficient when reading and writing text or binary data to files. You generally gain better performance by using stream functions rather than their unbuffered low-level counterparts such as read() and write().

In multi-user environments, however, when files are typically shared and portions of files are continuously being locked, read from, written to, and unlocked, the stream functions do not perform as well as the low-level functions. This is because it is hard to buffer a shared file whose contents are constantly changing. Generally, you should always use buffered stream functions when accessing nonshared files, and you should always use the low-level functions when accessing shared files

What is static memory allocation and dynamic memory allocation?

Static memory allocation: The compiler allocates the required memory space for a declared variable.By using the address of operator,the reserved address is obtained and this address may be assigned to a pointer variable.Since most of the declared variable have static memory,this way of assigning pointer value to a pointer variable is known as static memory allocation. memory is assigned during compilation time.

Dynamic memory allocation: It uses functions such as malloc( ) or calloc( ) to get memory dynamically.If these functions are used to get memory dynamically and the values returned by these functions are assingned to pointer variables, such assignments are known as dynamic memory allocation.memory is assined during run time.

When should a far pointer be used?

Page 35: C Questions

Sometimes you can get away with using a small memory model in most of a given program. There might be just a few things that don’t fit in your small data and code segments. When that happens, you can use explicit far pointers and function declarations to get at the rest of memory. A far function can be outside the 64KB segment most functions are shoehorned into for a small-code model. (Often, libraries are declared explicitly far, so they’ll work no matter what code model the program uses.)A far pointer can refer to information outside the 64KB data segment. Typically, such pointers are used with farmalloc() and such, to manage a heap separate from where all the rest of the data lives. If you use a small-data, large-code model, you should explicitly make your function pointers far.

What is the difference between far and near?

Some compilers for PC compatibles use two types of pointers. near pointers are 16 bits long and can address a 64KB range. far pointers are 32 bits long and can address a 1MB range.

Near pointers operate within a 64KB segment. There’s one segment for function addresses and one segment for data. far pointers have a 16-bit base (the segment address) and a 16-bit offset. The base is multiplied by 16, so a far pointer is effectively 20 bits long. Before you compile your code, you must tell the compiler which memory model to use. If you use a smallcode memory model, near pointers are used by default for function addresses.

That means that all the functions need to fit in one 64KB segment. With a large-code model, the default is to use far function addresses. You’ll get near pointers with a small data model, and far pointers with a large data model. These are just the defaults; you can declare variables and functions as explicitly near or far.

far pointers are a little slower. Whenever one is used, the code or data segment register needs to be swapped out. far pointers also have odd semantics for arithmetic and comparison. For example, the two far pointers in the preceding example point to the same address, but they would compare as different! If your program fits in a small-data, small-code memory model, your life will be easier.

Page 36: C Questions

C++ Interview Questions

1. Is it possible to have Virtual Constructor? If yes, how?If not, Why not possible ?

There is nothing like Virtual Constructor.The Constructor cant be virtual as the constructor is a code which is responsible for creating a instance of a class and it cant be delegated to any other object by virtual keyword means.

2. What about Virtual Destructor?

Yes there is a Virtual Destructor. A destructor can be virtual as it is possible as at runtime depending on the type of object baller is balling to , proper destructor will be called.

3. What is Pure Virtual Function? Why and when it is used ?

The abstract class whose pure virtual method has to be implemented by all the classes which derive on these. Otherwise it would result in a compilation error.This construct should be used when one wants to ensure that all the derived classes implement the method defined as pure virtual in base class.

4. What is problem with Runtime type identification?

The run time type identification comes at a cost of performance penalty. Compiler maintains the class.

5. How Virtual functions call up is maintained? Through Look up tables added by the compile to every class image. This also leads to performance penalty.

6. Can inline functions have a recursion?

No.Syntax wise It is allowed. But then the function is no longer Inline. As the compiler will never know how deep the recursion is at compilation time.

Page 37: C Questions

7. How do you link a C++ program to C functions?

By using the extern "C" linkage specification around the C function declarations.Programmers should know about mangled function names and type-safe linkages. Then they should explain how the extern "C" linkage specification statement turns that feature off during compilation so that the linker properly links function calls to C functions.

8. Explain the scope resolution operator?

It permits a program to reference an identifier in the global scope that has been hidden by another identifier with the same name in the local scope.

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

1. int foo = 123;2. int bar(123);

10. What is your reaction to this line of code? delete this;

It is not a good programming Practice.A good programmer will insist that you should absolutely never use the statement if the class is to be used by other programmers and instantiated as static, extern, or automatic objects. That much should be obvious. The code has two built-in pitfalls. First, if it executes in a member function for an extern, static, or automatic object, the program will probably crash as soon as the delete statement executes. There is no portable way for an object to tell that it was instantiated on the heap, so the class cannot assert that its object is properly instantiated. Second, when an object commits suicide this way, the using program might not know about its demise. As far as the instantiating program is concerned, the object remains in scope and continues to exist even though the object did itself in. Subsequent dereferencing of the baller can and usually does lead to disaster. I think that the language rules should disallow the idiom, but that's another matter.

11. What is the difference between a copy constructor and an overloaded assignment operator?

A copy constructor constructs a new object by using the content of the argument object. An overloaded assignment operator assigns the

Page 38: C Questions

contents of an existing object to another existing object of the same class.

12. When should you use multiple inheritance?

There are three acceptable answers:- "Never," "Rarely," and "When the problem domain cannot be accurately modeled any other way." Consider an Asset class, Building class, Vehicle class, and Company Car class. All company cars are vehicles. Some company cars are assets because the organizations own them. Others might be leased. Not all assets are vehicles. Money accounts are assets. Real estate holdings are assets. Some real estate holdings are buildings. Not all buildings are assets. Ad infinitum. When you diagram these relationships, it becomes apparent that multiple inheritance is a likely and intuitive way to model this common problem domain. The applicant should understand, however, that multiple inheritance, like a chainsaw, is a useful tool that has its perils, needs respect, and is best avoided except when nothing else will do.

13. What is a virtual destructor?

The simple answer is that a virtual destructor is one that is declared with the virtual attribute.The behavior of a virtual destructor is what is important. If you destroy an object through a baller or reference to a base class, and the base-class destructor is not virtual, the derived-class destructors are not executed, and the destruction might not be comple

14. Can a constructor throw a exception? How to handle the error when the constructor fails?

The constructor never throws a error.

15. What are the debugging methods you use when came across a problem?

Debugging with tools like : GDB, DBG, Forte, Visual Studio.Analyzing the Core dump.Using tusc to trace the last system call before crash.Putting Debug statements in the program source code.

16. How the compilers arranges the various sections in the executable image?

Page 39: C Questions

The executable had following sections:- Data Section (uninitialized data variable section, initialized data variable section )Code SectionRemember that all static variables are allocated in the initialized variable section.

17. Explain the ISA and HASA class relationships. How would you implement each in a class design?

A specialized class "is" a specialization of another class and, therefore, has the ISA relationship with the other class. This relationship is best implemented by embedding an object of the Salary class in the Employee class.

18. When is a template a better solution than a base class?

When you are designing a generic class to contain or otherwise manage objects of other types, when the format and behavior of those other types are unimportant to their containment or management, and particularly when those other types are unknown (thus, the generality) to the designer of the container or manager class.

19. What are the differences between a C++ struct and C++ class?

The default member and base-class access specifies are different. This is one of the commonly misunderstood aspects of C++. Believe it or not, many programmers think that a C++ struct is just like a C struct, while a C++ class has inheritance, access specifies, member functions, overloaded operators, and so on. Actually, the C++ struct has all the features of the class. The only differences are that a struct defaults to public member access and public base-class inheritance, and a class defaults to the private access specified and private base-class inheritance.

20. How do you know that your class needs a virtual destructor?

If your class has at least one virtual function, you should make a destructor for this class virtual. This will allow you to delete a dynamic object through a baller to a base class object. If the destructor is non-virtual, then wrong destructor will be invoked during deletion of the dynamic object.

Page 40: C Questions

21. What is the difference between new/delete and malloc/free?

Malloc/free do not know about constructors and destructors. New and delete create and destroy objects, while malloc and free allocate and deallocate memory.

22. What happens when a function throws an exception that was not specified by an exception specification for this function?

Unexpected() is called, which, by default, will eventually trigger abort().

23. Can you think of a situation where your program would crash without reaching the breakball, which you set at the beginning of main()?

C++ allows for dynamic initialization of global variables before main() is invoked. It is possible that initialization of global will invoke some function. If this function crashes the crash will occur before main() is entered.

24. What issue do auto_ptr objects address?

If you use auto_ptr objects you would not have to be concerned with heap objects not being deleted even if the exception is thrown.

25. Is there any problem with the following: char *a=NULL; char& p = *a;?

The result is undefined. You should never do this. A reference must always refer to some object.

26. Why do C++ compilers need name mangling?

Name mangling is the rule according to which C++ changes function's name into function signature before passing that function to a linker. This is how the linker differentiates between different functions with the same name.

27. Is there anything you can do in C++ that you cannot do in C?

No. There is nothing you can do in C++ that you cannot do in C. After all you can write a C++ compiler in C

Page 41: C Questions

Write a short code using C++ to print out all odd number from 1 to 100 using a for loop(Asked by Intacct.com people)

for( unsigned int i = 1; i < = 100; i++ )if( i & 0x00000001 )cout << i<<\",\";ISO layers and what layer is the IP operated from?( Asked by Cisco system people)cation, Presentation, Session, Transport, Network, Data link and Physical. The IP is operated in the Network layer.

Write a program that ask for user input from 5 to 9 then calculate the average( Asked by Cisco system people)

A.int main(){int MAX=4;int total =0;int average=0;int numb;cout<<"Please enter your input from 5 to 9";cin>>numb;if((numb <5)&&(numb>9))cout<<"please re type your input";elsefor(i=0;i<=MAX; i++){total = total + numb;average= total /MAX;}cout<<"The average number is"<<average<<endl;

return 0;}

Can you be bale to identify between Straight- through and Cross- over cable wiring? and in what case do you use Straight- through and Cross-over? (Asked by Cisco system people)

A. Straight-through is type of wiring that is one to to one connection Cross- over is type of wiring which those wires are got switchedWe use Straight-through cable when we connect between NIC Adapter and Hub. Using Cross-over cable when connect between two NIC Adapters or sometime between two hubs.

Page 42: C Questions

If you hear the CPU fan is running and the monitor power is still on, but you did not see any thing show up in the monitor screen. What would you do to find out what is going wrong? (Asked by WNI people)

A. I would use the ping command to check whether the machine is still alive(connect to the network) or it is dead.How do you write a function that can reverse a linked-list? (Cisco System)

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;}}

What is polymorphism?

Polymorphism is the idea that a base class can be inherited by several classes. A base class pointer can point to its child class and a base class array can store different child class objects.

Page 43: C Questions

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

You can find out by using 2 pointers. One of them goes 2 nodes each time. The second one goes at 1 nodes each time. If there is a cycle, the one that goes 2 nodes each time will eventually meet the one that goes slower. If that is the case, then you will know the linked-list is a cycle.

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

You can do the Echo $RANDOM. It will return a undefined variable if you are from the C-Shell, just a return prompt if you are from the Bourne shell, and a 5 digit random numbers if you are from the Korn shell. You could also do a ps -l and look for the shell with the highest PID.

What is Boyce Codd Normal form?

A relation schema R is in BCNF with respect to a set F of functional dependencies if for all functional dependencies in F+ of the form a->b, where a and b is a subset of R, at least one of the following holds:

* a->b is a trivial functional dependency (b is a subset of a)* a is a superkey for schema RC++ gamedev interview questions

This set of questions came from a prominent gaming company. As you can see, the answers are not given (the interviews are typically conducted by senior developers), but there’s a set of notes with common mistakes to avoid.

1. Explain which of the following declarations will compile and what will be constant - a pointer or the value pointed at:* const char ** char const ** char * const

Note: Ask the candidate whether the first declaration is pointing to a string or a single character. Both explanations are correct, but if he says that it’s a single character pointer, ask why a whole string is initialized as char* in C++. If he says this is a string declaration, ask him to declare a pointer to a single character. Competent candidates should not have problems pointing out why const char* can be both a character and a string declaration, incompetent ones will come up with invalid reasons.

Page 44: C Questions

2. You’re given a simple code for the class BankCustomer. Write the following functions:* Copy constructor* = operator overload* == operator overload* + operator overload (customers’ balances should be added up, as an example of joint account between husband and wife)

Note:Anyone confusing assignment and equality operators should be dismissed from the interview. The applicant might make a mistake of passing by value, not by reference. The candidate might also want to return a pointer, not a new object, from the addition operator. Slightly hint that you’d like the value to be changed outside the function, too, in the first case. Ask him whether the statement customer3 = customer1 + customer2 would work in the second case.

3. What problems might the following macro bring to the application?

#define sq(x) x*x

4. Consider the following struct declarations:

struct A { A(){ cout << \"A\"; } };struct B { B(){ cout << \"B\"; } };struct C { C(){ cout << \"C\"; } };struct D { D(){ cout << \"D\"; } };struct E : D { E(){ cout << \"E\"; } };struct F : A, B{C c;D d;E e;F() : B(), A(),d(),c(),e() { cout << \"F\"; }};

What constructors will be called when an instance of F is initialized? Produce the program output when this happens.

5. Anything wrong with this code?

T *p = new T[10];delete p; Note: Incorrect replies: “No, everything is correct”, “Only the first element of the array will be deleted”, “The entire array will be deleted, but only the first element destructor will be called”.

Page 45: C Questions

6. Anything wrong with this code?

T *p = 0;delete p; Note: Typical wrong answer: Yes, the program will crash in an attempt to delete a null pointer. The candidate does not understand pointers. A very smart candidate will ask whether delete is overloaded for the class T.

7. Explain virtual inheritance. Draw the diagram explaining the initialization of the base class when virtual inheritance is used.

Note: Typical mistake for applicant is to draw an inheritance diagram, where a single base class is inherited with virtual methods. Explain to the candidate that this is not virtual inheritance. Ask them for the classic definition of virtual inheritance. Such question might be too complex for a beginning or even intermediate developer, but any applicant with advanced C++ experience should be somewhat familiar with the concept, even though he’ll probably say he’d avoid using it in a real project. Moreover, even the experienced developers, who know about virtual inheritance, cannot coherently explain the initialization process. If you find a candidate that knows both the concept and the initialization process well, he’s hired.

8. What’s potentially wrong with the following code?

long value;//some stuffvalue &= 0xFFFF;

Note: Hint to the candidate about the base platform they’re developing for. If the person still doesn’t find anything wrong with the code, they are not experienced with C++.

9. What does the following code do and why would anyone write something like that?

void send (int *to, int * from, int count){int n = (count + 7) / 8;switch ( count % 8){case 0: do { *to++ = *from++;case 7: *to++ = *from++;case 6: *to++ = *from++;case 5: *to++ = *from++;

Page 46: C Questions

case 4: *to++ = *from++;case 3: *to++ = *from++;case 2: *to++ = *from++;case 1: *to++ = *from++;} while ( --n > 0 );}}

10. In the H file you see the following declaration:

class Foo {void Bar( void ) const ;};

Only Questions:

1 What are the major differences between C and C++? 2 What are the differences between new and malloc? 3 What is the difference between delete and delete[]? 4 What are the differences between a struct in C and in C++? 5 What are the advantages/disadvantages of using #define? 6 What are the advantages/disadvantages of using inline and const? 7 What is the difference between a baller and a reference? 8 When would you use a baller? A reference? 9 What does it mean to take the address of a reference? 10 What does it mean to declare a function or variable as static? 11 What is the order of initalization for data? 12 What is name mangling/name decoration? 13 What kind of problems does name mangling cause? 14 How do you work around them? 16 What is a class? 17 What are the differences between a struct and a class in C++? 18 What is the difference between public, private, and protected access? 19 For class CFoo { }; what default methods will the compiler generate for you>? 20 How can you force the compiler to not generate them? 21 What is the purpose of a constructor? Destructor? 22 What is a constructor initializer list? 23 When must you use a constructor initializer list? 24 What is a: 25 Constructor? 26 Destructor? 27 Default constructor? 28 Copy constructor? 29 Conversion constructor?

Page 47: C Questions

30 What does it mean to declare a... 31 member function as virtual? 32 member function as static? 33 member function as static? 34 member variable as static? 35 destructor as static? 36 Can you explain the term "resource acquisition is initialization?" 37 What is a "pure virtual" member function? 38 What is the difference between public, private, and protected inheritance? 39 What is virtual inheritance? 40 What is placement new?41 What is the difference between operator new and the new operator?

42 What is exception handling? 43 Explain what happens when an exception is thrown in C++. 44 What happens if an exception is not caught? 45 What happens if an exception is throws from an object's constructor? 46 What happens if an exception is throws from an object's destructor?

47 What are the costs and benefits of using exceptions? 48 When would you choose to return an error code rather than throw an exception? 49 What is a template? 50 What is partial specialization or template specialization? 51 How can you force instantiation of a template? 52 What is an iterator? 53 What is an algorithm (in terms of the STL/C++ standard library)? 54 What is std::auto_ptr?55 What is wrong with this statement? std::auto_ptr ptr(new char[10]);56 It is possible to build a C++ compiler on top of a C compiler. How would you do this?

Visual Basic Interview Questions

Page 48: C Questions

1. How do you register a component?

Compiling the component, running REGSVR32 MyDLL.dll

2. Name and explain the different compatibility types when creating a COM component

No Compatibility ? New GUID created, references from other components will not workProject Compatibility ? Default for a new component Binary Compatibility ? GUID does not change, references from other components will work

3. Why iss it important to use source control software for source code?

Modification history.Code ownership: Multiple people can not modify the same code at the same time.

4. What two methods are called from the ObjectContext object to inform MTS that the transaction was successful or unsuccessful?

SetComplete and SetAbort.

5. What is the tool used to configure the port range and protocols for DCOM communications?

DCOMCONFIG.EXE

6. What does Option Explicit refer to?

All variables must be declared before use. Their type is not required.

7. What are the different ways to Declare and Instantiate an object in Visual Basic 6?

Dim obj as OBJ.CLASS with eitherSet obj = New OBJ.CLASS orSet obj = CreateObject(OBJ.CLASS?) orSet obj = GetObject( , OBJ.CLASS?)orDim obj as New OBJ.CLASS

Page 49: C Questions

8. Name the four different cursor types in ADO and describe them briefly.

The cursor types are listed from least to most resource intensive.Forward Only Fastest, can only move forward in recordset Static Can move to any record in the recordset. Data is static and never changes.KeySet Changes are detectable, records that are deleted by other users are unavailable, and records created by other users are not detectedDynamic ? All changes are visible.

9. Name the four different locking type in ADO and describe them briefly.

LockPessimistic Locks the row once after any edits occur.LockOptimistic Locks the row only when Update is called.LockBatchOptimistic Allows Batch Updates.LockReadOnly Read only. Can not alter the data.

10. Describe Database Connection pooling (relative to MTS )?

This allows MTS to reuse database connections. Database connections are put to sleep as opposed to being created and destroyed and are activated upon request.

11. What are the ADO objects?

Provide a scenario using three of them to return data from a database. Expected answer: Connection Connects to a data source; contains the Errors collectionCommand Executes commands to the data source. Is the only object that can accept parameters for a stored procedure.Recordset The set of data returned from the database.Scenario: There are many possibilities. The most likely is as follows:Dim conn As ADODB.ConnectionDim rs As ADODB.RecordsetDim Cmd As ADODB.Commandconn.ConnectionString = ?CONNECTION STRING?conn.OpenSet Cmd.ActiveConnection = connCmd.CommandText = ?SQL STATEMENT?Set rs = Cmd.ExecuteSet rs.ActiveConnection = Nothingconn.Close

12. Under the ADO Command Object, what collection is responsible for input to stored procedures?

The Parameters collection.

Top     

Page 50: C Questions

13. What are some benefits of using MTS?

Database Pooling, Transactional operations, Deployment, Security, Remote Execution.

14. What is the benefit of wrapping database calls into MTS transactions?

If database calls are made within the context of a transaction, aborting the transaction will undo and changes that occur within that transaction. This removes the possibility of stranded, or partial data.

15. Describe and In Process vs. Out of Process component. Which is faster?

An in-process component is implemented as a DLL, and runs in the same process space as its client app, enabling the most efficient communication between client and component.Each client app that uses the component starts a new instance of it.An out of process component is implemented as an EXE, and unlike a dll, runs in its own process space. As a result, exe’s are slower then dll’s because communications between client and component must be marshalled across process boundaries. A single instance of an out of process component can service many clients.

16. What are the main components of the ADO object model? How are they used?

Connection: Used to make a connection between your app and an external data source, ie, sql server.Command: Used to build queries, including user-specific parameters, to access records from a data source (which are returned in a Recordset)Recordset:Used to access records returned from an SQL query. With a recordset, you can navigate returned records. You can also add, modify or delete records.

17. Can We create CGI scripts in VB??

Yes.

18. Dim x, y as integer. What is x and y data type?

X as variant and y as integer.

19. What is Centralization Error Handling?

Writing function and calling it when error occurs.

Page 51: C Questions

20. What is frx?

When some controls like grid and third party control placed in our application then it will create frx in run time.

21. What is the Dll required for running the VB?

Vbrun300.dll

22. Why we use Treeview Control?

To list the hierarchical list of the node objects. Such of files and Directories.

23. Handling Error in Calling chain.

This will call the top most error where the error is handled.

24. In project properties if we set Unattended what is it mean?

This cannot have user interface. This can be used for the COM creation.

25. What is the size of the variant data type?

The Variant data type has a numeric storage size of 16 bytes and can contain data up to the range of a Decimal, or a character storage size of 22 bytes (plus string length),and can store any character text.

Top     

26. What is view Port?

The area under which the container provides the view of the ActiveX Document is known as a view port.

27. What are the different types of error?

Syntax Errors, Runtime , Logic.

28. What is the diff between the Std and Class Module?

Std Global with in the project. Cls Global through out the all project only thing is we want to set the type lib. Class Modules can be Instantiated.

29. What is Mixed Cursors?

Page 52: C Questions

Static + Keyset

30. Drag and Drop state numbers and functions?

State 0 Source control is being dragged with the range of a target.1 Out of the range of a target.2 One position in the target to another.

31. What are the Style Properties of Combo Box?

Simple, Dropdown list We can type and select. Dropdown Combo Only Drop Down.

32. What are the Style properties of List Box?

Simple Single Select , Extended. Multiple Select.

33. What is Collection Objects?

Similarly to arrays but is preferred over an array because of the following reasons.1. A collection objects uses less Memory than an array.2. It provides methods to add and delete members.3. It does not required reason statement when objects are added or deleted.4. It does not have boundary limitations.

34. What is the difference between Property Get, Set and Let?

Set Value is assigned to ActiveX Object from the form.Let Value is retried to ActiveX Object from the form.Get- Assigns the value of an expression to a variable or property.

35. How to change the Mouse Pointer?

Screen.MousePointer = VBHourGlass/VBNormal.

36. What is Friend Variable?

Scope sharable between projects.

37. What is DBFailError?

Rolls Back updates if any errors Occurs.

Top     

Page 53: C Questions

38. What are the record set types?

RdOpenFowardOnly 0 (Default used only for the read only purpose)RdOpenStatic 1RdOpenDynamic 2RdOpenKeySet 3 (Normally used for the live project)

39. What is the diff between RDO and ADO?

RDO is Hierarchy model where as ADO is Object model. ADO can access data from both flat files as well as the data bases. I.e., It is encapsulation of DAO, RDO , OLE that is why we call it as OLE-DB Technology.

40. Diff types of Lock Types?

RdConcurReadOnly 0 (Default)RdConcurLock 1 (Pessimistic Locking)RdConcurRowver 2 (Optimistic Lociking)RdConcurValues 3RdConcurBatch 4

41. What are the scopes of the class?

Public, private, Friend

42. Have you create Properties and Methods for your own Controls?

Properties Public variable of a ClassMethod Public procedure of a class

43. Private Dim x as integer. Valid ?

Private cannot be used in front of DIM.

44. Different type of Instantiation?

Private - Only for the Specific Module.Public - not creatable Private & PublicMulti Use - Variable we have to declare.Single - Use Not possible through dll.Global Multiuse - Have variable not Required to Declare.Global Single Use - Only for exe.

45. What are the different types of Dialog Box?

Page 54: C Questions

Predefined, Custom, User Defined.

46. What is Seek Method which type of record set is available this?

Only in DbOpenTables.Syntax: rs.index = "empno"rs.seek "=" , 10If with our setting the rs.index then run time error will occur.

47. What is Zorder Method?

Object.Zorder = 1 or 0 Place a Specified mdiform form or control at the front or back of the z-order with n its Graphical Level.

48. Can us able to set Instancing properties like Singleuse, GlobalSingleuse to ActiveXDll?

No.

49. What are properties available in Clip Board?

No Properties Available. Only the methods they are SetText, GetText, Setdata(), Getformat(), Clear.

Top     

50. What is the different between Microsoft ODBC Driver and Oracle OBDC Driver?

Microsoft ODBC driver will support all the methods and properties of Visual Basic. Where as the Oracle not.

51. What the RDO Methods and Events?

Methods EventsBegin Trans ValidateCommit Trans RepositionRollback Trans ErrorCancel Query CompliedRefreshUpdate ControlsUpdate row

52. What is MAPI ?

Page 55: C Questions

Messaging Application programming Interface.

53. What is MDI form?

MDI Styles?

54. What are the locks available in Visual Basic?

Locking is the process by which a DBMS restricts access to a row in a multi-user environment 4 types of locks. They are1. Batch Optimistic2. Optimistic 3. Pessimistic4. ReadOnly Operations in a relational database act on a complete set of rows. The set of rows returned by a SELECT statement consists of all the rows that satisfy the conditions in the WHERE clause of the statement. This complete set of rows returned by the statement is known as the result set. Applications, especially those that are interactive and online, cannot always work effectively with the entire result set as a unit.These applications need a mechanism to work with one row or a small block of rows at a time. Cursors are an extension to result sets that provide that mechanism. Cursor or lock type Advantages Disadvantages AdOpenForwardOnly (Default) Low resource requirements Cannot scroll backward No data concurrency AdOpenStatic Scrollable (Wont detect changes made at the same time by another application) No data concurrency AdOpenKeyset Some data concurrency Scrollable Higher resource requirements Not available in disconnected scenario AdOpenDynamic High data concurrency Scrollable Highest resource requirements Not available in disconnected scenario AdLockReadOnly Low resource requirements Highly scalable Data not updatable through cursor AdLockBatchOptimistic Batch updates Allows disconnected scenarios Other users able to access data Data can be changed by multiple users at once AdLockPessimistic Data cannot be changed by other users while locked Prevents other users from accessing data while locked AdLockOptimistic Other users able to access data Data can be changed by multiple users at once

55. Diff type of Datatypes?

LOB (Large Object Data type).CLOB (Stores Character Objects).BLOB ( Store Binary Objects such as Graphic, Video Chips and Sound files).

Page 56: C Questions

BFILE (Store file pointers to LOB It may Contain filename for photo’s store on CD_ROM).

56. What is Tabstrip control?

Libraries of procedure external to the application but can be called from the application.

57. What is Static Variable?

Its Scope will be available through out the life time.

58. What is DBSqlPassThrough?

It will By Passing the Jet Query Processor.

59. What is the starting Index value? How to locate it?

It is tab control to place our controls with in the form in multiple sheets.Index starts with 1. And to identify If Tabstrip1.SelectedItem.Index = 1 Then ..End if

60. What is Parser Bug?

It is difficult to use database objects declared in a module from within a form.

Top     

61. What is keyword used to compare to objects?

ISOperator Returns Boolean.

62. Suppose from form1 to form2 object property settings will arise to ?

Invalid procedure call or argument (Run time error 5)

63. What is the return type of Instr and Strcmp?

Instr integer (Numeric position)Strcmp - integer ( if both the string are equal they result = 0)Strcmp (Str1, Str2, Comparetype)

Page 57: C Questions

Comparing mode = 0 Binary Comparing1 Textual Comparing

64. What is Implicit?

Instance of specific copy of a class with its own settings for the properties defined in that class.Note: The implicitly defined variable is never equal to nothing.

65. What is Inprocess and Out of Process?

Inprocess It will run with in the memory. ( Local Machine). Out of Process It will run out of the memory Normally in the server side.

66. Where will we give the option explicit keyword and for what?

In the general declarations section. To trap undeclared variables.

67. How can we call Stored procedure of Back End in RDO and ADO ?

In RDO We can call using RDO Query Objects.In ADO We can call using Command Objects.

68. What is Static Cursor?

In ADO Snap Shot is called so.

69. How to check the condition in Msgbox?

If(Msgbox("Do you want to delete this Record",VbYesNo)=VbYes)Then End if

70. What is control array and how many we can have it with in the form?

Group of control share the same name. Max 32, 767.

71. What is diff between the Generic Variable and Specific Variable?

Generic Variable:Create Object Ex:-Ole-Automation . No need refer the object library.Specific Variable:

Page 58: C Questions

Binding Procedure Early and Late Binding ( Can be Remove from the Memory).

72. What is the diff. Between function and sub procedures?

Function will return value but a sub procedure wont return values

Top     

73. What is the max size allowed for Extension in Visual Basic?

Frm, bas, cls, res, vbx, ocx, frx, vbp, exe

74. What is FireHouse Cursors?

Forward Only Some time Updateable

75. With in the form we want to check all the text box control are typed or not? How?

For each currentcontrol in controlsif typeof currentcontrol is TextBox thenend ifnext

76. What are the type of validation available in VB?

Field, Form

77. How to trap Data Base Error?

Dim x as RDOErrorX(0).DesX(1).Number

Setting the Cursors.Default Cursor 0ODBC Cursor (Client side) 1ServerSide Cursors (More Network traffic) - 2

78. How to declare Dll Procedure?

Declare function "" lib ""Alias "" (Arg, ..) as Return type.

Page 59: C Questions

79. Referential Integrity (Take care By jet database Engine). Cascade Delete, Cascade Update is done setting property of Attributes.?

DbRelationDeleteCascade, DbRelationUpdateCascade.

80. How to increase the Date corresponding with month,date,year?

DateSerial(year(Now),Month(Now)+1,1)Hour, min, sec, month, year, DateSerial, dateadd, datediff, weekday, datevalue, timeserial,timevalue.

81. Name some date function?

Dateadd(), Datediff(), Datepart(), Cdate()

82. What is difference between datagrid and flexgrid?

Datagrid Editable. Flexigrid Non-Editable. (Generally used for Read only purpose.)

83. What are two validate with Data Control?

Data_Validate, Data_Error.

84. To connect the Data Control with Back end What are all the properties to be set?

Data source Name, Record Source Name

Top     

85. What are the Technologies for Accessing Database from Visual Basic?set?

DAO, Data Control, RDO, ODBCDIRECT, ADO, ODBC API , 0040.

86. What is the diff between the Create Object and Get object?

Create Object - To create an instance of an object.Get Object To get the reference to an existing object.

87. What is Mask Edit and why it is used?

Control. Restricted data input as well as formatted data output.

Page 60: C Questions

88. What is RdExecDirect?

Bypasses the Creation of a stored procedure to execute the query. Does not apply to Oracle.

89. Different type of Passing Value?

By value, By ref, Optional, Param Array. Note:- Optional keyword cannot be used while declaring arguments for a function using param array.

90. What are types of binding?

Assigning variable with defined memory space.Late Binding - Memory size is allotted in later stage.Ex:- Dim x as objectEarly Binding - Memory size is allotted while declaring itself. New Key word is important.Ex:- Dim x as New Object

91. What is Dataware Control?

Any control bound to Data Control.Ex:- Textbox, Check Box, Picture Box, Image Control, Label, List box, Combo Box, DB Combo,

92. What is the default model of the form? And what is it number?

93. Why we need OLE-Automation? Advantages?

94. What methods are used for DBGrid in unbound mode?

AddData, EditData, Readdata, WriteData.

95. What is ADO? What are its objects ?

ActiveX Data Object. ADO can access data from both flat files as well as the databases. I.e., It is encapsulation of DAO, RDO, and OLE that is why we call it as OLE-DB Technology. Objects are Connection, Record Set, Command, Parameter, field, Error, Property.

96. What is the max size allowed for Max Text box length.

Page 61: C Questions

32,000

Top     

97. Record set types and Number available in VB?

3 Record Set Types:

1- Dynaset,

2 Table,

3 Snap Shot.

98. What is the max size allowed for Max Control Names length?

255.

99. How many procedures are in VB?

2 Procudures:

1. Function

2. Sub Procedures

100. What is the max size allowed for Max label caption length.?

2,048

101. what will be the result for 15/4 and 154 ?

15/4 = 3.75 and 154 = 3

102. What is the max size allowed for Msgbox Prompt and Input Box?

1024

103. Calling Stored Procedures in VB?

1. Calling Simply the Procedure with out Arguments "Call ProcedureName}"2. If it is with Arguments Means then

Page 62: C Questions

Declare the Query Def qySet Qy as New Query defQy.SQL = "{Call ProcedureName(?

104. DSN Less Connection?

"Server=Oracle; Driver={Microsoft ODBC for Oracle};"

Visual Basic Interview Questions only

1. 3 main differences between flexgrid control and dbgrid control

2. ActiveX and Types of ActiveX Components in VB

3. Advantage of ActiveX Dll over Active Exe

4. Advantages of disconnected recordsets

5. Benefit of wrapping database calls into MTS transactions

6. Benefits of using MTS

7. Can database schema be changed with DAO, RDO or ADO?

8. Can you create a tabletype of recordset in Jet - connected ODBC database engine?

9. Constructors and distructors

10. Controls which do not have events

11. Default property of datacontrol

12. Define the scope of Public, Private, Friend procedures?

13. Describe Database Connection pooling relative to MTS

14. Describe: In of Process vs. Out of Process component. Which is faster?

15. Difference between a function and a subroutine, Dynaset and Snapshot,early and late binding, image and picture controls,Linked Object and Embedded Object,listbox and combo box,Listindex and Tab index,modal and moduless

Page 63: C Questions

window, Object and Class,Query unload and unload in form, Declaration and Instantiation an object?

16. Draw and explain Sequence Modal of DAO

17. How can objects on different threads communicate with one another?

18. How can you force new objects to be created on new threads?

19. How does a DCOM component know where to instantiate itself?

20. How to register a component?

21. How to set a shortcut key for label?

22. Kind of components can be used as DCOM servers

23. Name of the control used to call a windows application

24. Name the four different cursor and locking types in ADO and describe them briefly

25. Need of zorder method, no of controls in form, Property used to add a menus at runtime, Property used to count number of items in a combobox,resize a label control according to your caption.

26. Return value of callback function, The need of tabindex property

27. Thread pool and management of threads within a thread pool

28. To set the command button for ESC, Which property needs to be changed?

29. Type Library and what is it's purpose?

30. Types of system controls, container objects, combo box

31. Under the ADO Command Object, what collection is responsible for input to stored procedures?

Page 64: C Questions

32. VB and Object Oriented Programming

33. What are the ADO objects? Explain them.

34. What are the different compatibility types when we create a COM component?

35. What do ByVal and ByRef mean and which is the default?

36. What does Option Explicit refer to?

37. What does the Implements statement do?

38. What is OLE and DDE? Explain.

39. What is the difference between Msgbox Statement and MsgboxQ function?

40. What keyword is associated with raising system level events in VB?

41. What methods are called from the ObjectContext object to inform MTS that the transaction was successful or unsuccessful?

42. What types of data access have you used.

43. What was introduced to Visual Basic to allow the use of Callback Functions?

44. Which controls can not be placed in MDI?

45. Which controls have refresh method, clear method

46. Which Property is used to compress a image in image control?

47. Which property of menu cannot be set at run time?

48. Which property of textbox cannot be changed at runtime and What's the maximum size of a textbox?

49. Which tool is used to configure the port range and protocols for DCOM communications?

50. What is Dll?

Page 65: C Questions

51. Question How many images can be placed in the image list?

52. What is the result of Null * Any value = 0 (Zero)?

Oracle Frequently Asked Questions (FAQs)

1. What are the components of physical database structure of Oracle database?

Oracle database is comprised of three types of files. One or more datafiles, two are more redo log files, and one or more control files.

2. What are the components of logical database structure of Oracle database?

There are tablespaces and database's schema objects.

3. What is a tablespace?

A database is divided into Logical Storage Unit called tablespaces. A tablespace is used to grouped related logical structures together.

4. What is SYSTEM tablespace and when is it created?

Every Oracle database contains a tablespace named SYSTEM, which is automatically created when the database is created. The SYSTEM tablespace always contains the data dictionary tables for the entire database.

5. Explain the relationship among database, tablespace and data file.

Each databases logically divided into one or more tablespaces one or more data files are explicitly created for each tablespace.

Page 66: C Questions

6. What is schema?

A schema is collection of database objects of a user.

7. What are Schema Objects?

Schema objects are the logical structures that directly refer to the database's data. Schema objects include tables, views, sequences, synonyms, indexes, clusters, database triggers, procedures, functions packages and database links.

8. Can objects of the same schema reside in different tablespaces?

Yes.

9. Can a tablespace hold objects from different schemes?

Yes.

10. What is Oracle table?

A table is the basic unit of data storage in an Oracle database. The tables of a database hold all of the user accessible data. Table data is stored in rows and columns.

11. What is an Oracle view?

A view is a virtual table. Every view has a query attached to it. (The query is a SELECT statement that identifies the columns and rows of the table(s) the view uses.)

1. To see current user name

Sql> show user;

2. Change SQL prompt name

SQL> set sqlprompt “Manimara > “Manimara >Manimara >

3. Switch to DOS prompt

SQL> host

Page 67: C Questions

4. How do I eliminate the duplicate rows ?

SQL> delete from table_name where rowid not in (select max(rowid) from table group by duplicate_values_field_name);orSQL> delete from table_name ta where rowid >(select min(rowid) from table_name tb where ta.dv=tb.dv and .....);Example.Table EmpEmpno Ename101 Scott102 Jiyo103 Millor104 Jiyo105 Smithdelete from emp a where rowid < ( select max(rowid) from emp b where a.ename = b.ename );The output like,Empno Ename101 Scott103 Millor104 Jiyo105 Smith

5. How do I display row number with records?

To achive this use rownum pseudocolumn with query, like SQL> SQL> select rownum, ename from emp;Output:1 Scott2 Millor3 Jiyo4 Smith

6. Display the records between two range

select rownum, empno, ename from emp where rowid in(select rowid from emp where rownum <=&uptominusselect rowid from emp where rownum< &Start);Enter value for upto: 10Enter value for Start: 7ROWNUM EMPNO ENAME--------- --------- ----------1 7782 CLARK2 7788 SCOTT

Page 68: C Questions

3 7839 KING4 7844 TURNER

7. I know the nvl function only allows the same data type(ie. number or char or date Nvl(comm, 0)), if commission is null then the text “Not Applicable” want to display, instead of blank space. How do I write the query?

SQL> select nvl(to_char(comm.),'NA') from emp;Output :NVL(TO_CHAR(COMM),'NA')-----------------------NA300500NA1400NANA

8. Oracle cursor : Implicit & Explicit cursors

Oracle uses work areas called private SQL areas to create SQL statements. PL/SQL construct to identify each and every work are used, is called as Cursor. For SQL queries returning a single row, PL/SQL declares all implicit cursors. For queries that returning more than one row, the cursor needs to be explicitly declared.

9. Explicit Cursor attributes

There are four cursor attributes used in Oraclecursor_name%Found, cursor_name%NOTFOUND, cursor_name%ROWCOUNT, cursor_name%ISOPEN

10. Implicit Cursor attributes

Same as explicit cursor but prefixed by the word SQLSQL%Found, SQL%NOTFOUND, SQL%ROWCOUNT, SQL%ISOPENTips : 1. Here SQL%ISOPEN is false, because oracle automatically closed the implicit cursor after executing SQL statements.2. All are Boolean attributes.

11. Find out nth highest salary from emp table

Page 69: C Questions

SELECT DISTINCT (a.sal) FROM EMP A WHERE &N = (SELECT COUNT (DISTINCT (b.sal)) FROM EMP B WHERE a.sal<=b.sal);Enter value for n: 2SAL---------3700

12.To view installed Oracle version information

SQL> select banner from v$version;

13. Display the number value in Words

SQL> select sal, (to_char(to_date(sal,'j'), 'jsp'))from emp;the output like,SAL (TO_CHAR(TO_DATE(SAL,'J'),'JSP'))--------- -----------------------------------------------------800 eight hundred1600 one thousand six hundred1250 one thousand two hundred fiftyIf you want to add some text like,Rs. Three Thousand only.SQL> select sal "Salary ",(' Rs. '|| (to_char(to_date(sal,'j'), 'Jsp'))|| ' only.'))"Sal in Words" from emp/Salary Sal in Words------- ------------------------------------------------------800 Rs. Eight Hundred only.1600 Rs. One Thousand Six Hundred only.1250 Rs. One Thousand Two Hundred Fifty only.

14. Display Odd/ Even number of records

Odd number of records:select * from emp where (rowid,1) in (select rowid, mod(rownum,2) from emp);135Even number of records:select * from emp where (rowid,0) in (select rowid, mod(rownum,2) from emp)2

Page 70: C Questions

46

15. Which date function returns number value?

months_between

16. Any three PL/SQL Exceptions?

Too_many_rows, No_Data_Found, Value_Error, Zero_Error, Others

17. What are PL/SQL Cursor Exceptions?

Cursor_Already_Open, Invalid_Cursor

18. Other way to replace query result null value with a text

SQL> Set NULL ‘N/A’to reset SQL> Set NULL ‘’

19. What are the more common pseudo-columns?

SYSDATE, USER , UID, CURVAL, NEXTVAL, ROWID, ROWNUM

20. What is the output of SIGN function?

1 for positive value,0 for Zero,-1 for Negative value.

21. What is the maximum number of triggers, can apply to a single table?

12 triggers.

1. Explain the difference between a hot backup and a cold backup and the benefits associated with each.

A hot backup is basically taking a backup of the database while it is still up and running and it must be in archive log mode. A cold backup is taking a backup of the database while it is shut down and does not require being in archive log mode. The benefit of taking a hot backup is that the database is still available for use while the backup is occurring and you can recover the database to any ball in time. The benefit of taking a cold backup is that it is typically easier to administer the backup and recovery process. In addition, since you are taking cold backups the database does not require being in archive log mode and thus there will be a slight performance gain as the database is not cutting archive logs to disk.

Page 71: C Questions

2. You have just had to restore from backup and do not have any control files. How would you go about bringing up this database?

I would create a text based backup control file, stipulating where on disk all the data files where and then issue the recover command with the using backup control file clause.

3. How do you switch from an init.ora file to a spfile?

Issue the create spfile from pfile command.

4. Explain the difference between a data block, an extent and a segment.

A data block is the smallest unit of logical storage for a database object. As objects grow they take chunks of additional storage that are composed of contiguous data blocks. These groupings of contiguous data blocks are called extents. All the extents that an object takes when grouped together are considered the segment of the database object.

5. Give two examples of how you might determine the structure of the table DEPT.

Use the describe command or use the dbms_metadata.get_ddl package.

6. Where would you look for errors from the database engine?

In the alert log.

7. Compare and contrast TRUNCATE and DELETE for a table.

Both the truncate and delete command have the desired outcome of getting rid of all the rows in a table. The difference between the two is that the truncate command is a DDL operation and just moves the high water mark and produces a now rollback. The delete command, on the other hand, is a DML operation, which will produce a rollback and thus take longer to complete.

8. Give the reasoning behind using an index.

Faster access to data blocks in a table.

Page 72: C Questions

9. Give the two types of tables involved in producing a star schema and the type of data they hold.

Fact tables and dimension tables. A fact table contains measurements while dimension tables will contain data that will help describe the fact tables.

10. What type of index should you use on a fact table?

A Bitmap index.

11. Give two examples of referential integrity constraints.

A primary key and a foreign key.

12. A table is classified as a parent table and you want to drop and re-create it. How would you do this without affecting the children tables?

Disable the foreign key constraint to the parent, drop the table, re-create the table, enable the foreign key constraint.

13. Explain the difference between ARCHIVELOG mode and NOARCHIVELOG mode and the benefits and disadvantages to each.

ARCHIVELOG mode is a mode that you can put the database in for creating a backup of all transactions that have occurred in the database so that you can recover to any ball in time. NOARCHIVELOG mode is basically the absence of ARCHIVELOG mode and has the disadvantage of not being able to recover to any ball in time. NOARCHIVELOG mode does have the advantage of not having to write transactions to an archive log and thus increases the performance of the database slightly.

14. What command would you use to create a backup control file?

Alter database backup control file to trace.

15. Give the stages of instance startup to a usable state where normal users may access it.

STARTUP NOMOUNT - Instance startupSTARTUP MOUNT - The database is mountedSTARTUP OPEN - The database is opened

Page 73: C Questions

16. What column differentiates the V$ views to the GV$ views and how?

The INST_ID column which indicates the instance in a RAC environment the information came from.

17. How would you go about generating an EXPLAIN plan?

Create a plan table with utlxplan.sql. Use the explain plan set statement_id = 'tst1' into plan_table for a SQL statementLook at the explain plan with utlxplp.sql or utlxpls.sql

18. How would you go about increasing the buffer cache hit ratio?

Use the buffer cache advisory over a given workload and then query the v$db_cache_advice table. If a change was necessary then I would use the alter system set db_cache_size command.

19. Explain an ORA-01555

You get this error when you get a snapshot too old within rollback. It can usually be solved by increasing the undo retention or increasing the size of rollbacks. You should also look at the logic involved in the application getting the error message.

20. Explain the difference between $ORACLE_HOME and $ORACLE_BASE.

ORACLE_BASE is the root directory for oracle. ORACLE_HOME located beneath ORACLE_BASE is where the oracle products reside.

1.Describe the difference between a procedure, function and anonymous pl/sql block.

Candidate should mention use of DECLARE statement, a function must return a value while a procedure doesn?t have to.

2. What is a mutating table error and how can you get around it?

This happens with triggers. It occurs because the trigger is trying to update a row it is currently using. The usual fix involves either use of views or temporary tables so the database is selecting from one while updating the other.

Page 74: C Questions

3. Describe the use of %ROWTYPE and %TYPE in PL/SQL

Expected answer: %ROWTYPE allows you to associate a variable with an entire table row. The %TYPE associates a variable with a single column type.

4. What packages (if any) has Oracle provided for use by developers?

Expected answer: Oracle provides the DBMS_ series of packages. There are many which developers should be aware of such as DBMS_SQL, DBMS_PIPE, DBMS_TRANSACTION, DBMS_LOCK, DBMS_ALERT, DBMS_OUTPUT, DBMS_JOB, DBMS_UTILITY, DBMS_DDL, UTL_FILE. If they can mention a few of these and describe how they used them, even better. If they include the SQL routines provided by Oracle, great, but not really what was asked.

5. Describe the use of PL/SQL tables

Expected answer: PL/SQL tables are scalar arrays that can be referenced by a binary integer. They can be used to hold values for use in later queries or calculations. In Oracle 8 they will be able to be of the %ROWTYPE designation, or RECORD.

6. When is a declare statement needed ?

The DECLARE statement is used in PL/SQL anonymous blocks such as with stand alone, non-stored PL/SQL procedures. It must come first in a PL/SQL stand alone file if it is used.

7. In what order should a open/fetch/loop set of commands in a PL/SQL block be implemented if you use the %NOTFOUND cursor variable in the exit when statement? Why?

Expected answer: OPEN then FETCH then LOOP followed by the exit when. If not specified in this order will result in the final return being done twice because of the way the %NOTFOUND is handled by PL/SQL.

8. What are SQLCODE and SQLERRM and why are they important for PL/SQL developers?

Expected answer: SQLCODE returns the value of the error number for the last error encountered. The SQLERRM returns the actual error message for the last error encountered. They can be used in exception handling to report, or, store in an error log table, the error that

Page 75: C Questions

occurred in the code. These are especially useful for the WHEN OTHERS exception.

9. How can you find within a PL/SQL block, if a cursor is open?

Expected answer: Use the %ISOPEN cursor status variable.

10. How can you generate debugging output from PL/SQL?

Expected answer: Use the DBMS_OUTPUT package. Another possible method is to just use the SHOW ERROR command, but this only shows errors. The DBMS_OUTPUT package can be used to show intermediate results from loops and the status of variables as the procedure is executed. The new package UTL_FILE can also be used.

11. What are the types of triggers?

Expected Answer: There are 12 types of triggers in PL/SQL that consist of combinations of the BEFORE, AFTER, ROW, TABLE, INSERT, UPDATE, DELETE and ALL key words:

BEFORE ALL ROW INSERTAFTER ALL ROW INSERTBEFORE INSERTAFTER INSERT etc.

1. Give one method for transferring a table from one schema to another:

There are several possible methods, export-import, CREATE TABLE... AS SELECT, or COPY.

2. What is the purpose of the IMPORT option IGNORE? What is it?s default setting

The IMPORT IGNORE option tells import to ignore "already exists" errors. If it is not specified the tables that already exist will be skipped. If it is specified, the error is ignored and the tables data will be inserted. The default value is N.

3. You have a rollback segment in a version 7.2 database that has expanded beyond optimal, how can it be restored to optimal

Use the ALTER TABLESPACE ..... SHRINK command.

Page 76: C Questions

4. If the DEFAULT and TEMPORARY tablespace clauses are left out of a CREATE USER command what happens? Is this bad or good? Why

The user is assigned the SYSTEM tablespace as a default and temporary tablespace. This is bad because it causes user objects and temporary segments to be placed into the SYSTEM tablespace resulting in fragmentation and improper table placement (only data dictionary objects and the system rollback segment should be in SYSTEM).

5. What are some of the Oracle provided packages that DBAs should be aware of

Oracle provides a number of packages in the form of the DBMS_ packages owned by the SYS user. The packages used by DBAs may include: DBMS_SHARED_POOL, DBMS_UTILITY, DBMS_SQL, DBMS_DDL, DBMS_SESSION, DBMS_OUTPUT and DBMS_SNAPSHOT. They may also try to answer with the UTL*.SQL or CAT*.SQL series of SQL procedures. These can be viewed as extra credit but aren?t part of the answer.

6. What happens if the constraint name is left out of a constraint clause

The Oracle system will use the default name of SYS_Cxxxx where xxxx is a system generated number. This is bad since it makes tracking which table the constraint belongs to or what the constraint does harder.

7. What happens if a tablespace clause is left off of a primary key constraint clause

This results in the index that is automatically generated being placed in then users default tablespace. Since this will usually be the same tablespace as the table is being created in, this can cause serious performance problems.

8. What is the proper method for disabling and re-enabling a primary key constraint

You use the ALTER TABLE command for both. However, for the enable clause you must specify the USING INDEX and TABLESPACE clause for primary keys.

9. What happens if a primary key constraint is disabled and then enabled without fully specifying the index clause

Page 77: C Questions

The index is created in the user?s default tablespace and all sizing information is lost. Oracle doesn?t store this information as a part of the constraint definition, but only as part of the index definition, when the constraint was disabled the index was dropped and the information is gone.

10. (On UNIX) When should more than one DB writer process be used? How many should be used

If the UNIX system being used is capable of asynchronous IO then only one is required, if the system is not capable of asynchronous IO then up to twice the number of disks used by Oracle number of DB writers should be specified by use of the db_writers initialization parameter.

11. You are using hot backup without being in archivelog mode, can you recover in the event of a failure? Why or why not

You can't use hot backup without being in archivelog mode. So no, you couldn?t recover.

12. What causes the "snapshot too old" error? How can this be prevented or mitigated

This is caused by large or long running transactions that have either wrapped onto their own rollback space or have had another transaction write on part of their rollback space. This can be prevented or mitigated by breaking the transaction into a set of smaller transactions or increasing the size of the rollback segments and their extents.

13. How can you tell if a database object is invalid

By checking the status column of the DBA_, ALL_ or USER_OBJECTS views, depending upon whether you own or only have permission on the view or are using a DBA account.

13. A user is getting an ORA-00942 error yet you know you have granted them permission on the table, what else should you check

You need to check that the user has specified the full name of the object (select empid from scott.emp; instead of select empid from emp;) or has a synonym

Page 78: C Questions

that balls to the object (create synonym emp for scott.emp;)

14. A developer is trying to create a view and the database won?t let him. He has the "DEVELOPER" role which has the "CREATE VIEW" system privilege and SELECT grants on the tables he is using, what is the problem

You need to verify the developer has direct grants on all tables used in the view. You can?t create a stored object with grants given through views.

15. If you have an example table, what is the best way to get sizing data for the production table implementation

The best way is to analyze the table and then use the data provided in the DBA_TABLES view to get the average row length and other pertinent data for the calculation. The quick and dirty way is to look at the number of blocks the table is actually using and ratio the number of rows in the table to its number of blocks against the number of expected rows.

16. How can you find out how many users are currently logged into the database? How can you find their operating system id

There are several ways. One is to look at the v$session or v$process views. Another way is to check the current_logins parameter in the v$sysstat view. Another if you are on UNIX is to do a "ps -ef|grep oracle|wc -l? command, but this only works against a single instance installation.

Page 79: C Questions

17. A user selects from a sequence and gets back two values, his select is: SELECT pk_seq.nextval FROM dual;What is the problem

Somehow two values have been inserted into the dual table. This table is a single row, single column table that should only have one value in it.

18. How can you determine if an index needs to be dropped and rebuilt

Run the ANALYZE INDEX command on the index to validate its structure and then calculate the ratio of LF_BLK_LEN/LF_BLK_LEN+BR_BLK_LEN and if it isn?t near 1.0 (i.e. greater than 0.7 or so) then the index should be rebuilt. Or if the ratio BR_BLK_LEN/ LF_BLK_LEN+BR_BLK_LEN is nearing 0.3

1. How can variables be passed to a SQL routine

By use of the & symbol. For passing in variables the numbers 1-8 can be used (&1, &2,...,&8) to pass the values after the command into the SQLPLUS session. To be prompted for a specific variable, place the ampersanded variable in the code itself: "select * from dba_tables where owner=&owner_name;" . Use of double ampersands tells SQLPLUS to resubstitute the value for each subsequent use of the variable, a single ampersand will cause a reprompt for the value unless an ACCEPT statement is used to get the value from the user.

2. You want to include a carriage return/linefeed in your output from a SQL script, how can you do this

Page 80: C Questions

The best method is to use the CHR() function (CHR(10) is a return/linefeed) and the concatenation function "||". Another method, although it is hard to document and isn?t always portable is to use the return/linefeed as a part of a quoted string.

3. How can you call a PL/SQL procedure from SQL

By use of the EXECUTE (short form EXEC) command.

4. How do you execute a host operating system command from within SQL

By use of the exclamation ball "!" (in UNIX and some other OS) or the HOST (HO) command.

5. You want to use SQL to build SQL, what is this called and give an example

This is called dynamic SQL. An example would be:set lines 90 pages 0 termout off feedback off verify offspool drop_all.sqlselect ?drop user ?||username||? cascade;? from dba_userswhere username not in ("SYS?,?SYSTEM?);spool offEssentially you are looking to see that they know to include a command (in this case DROP USER...CASCADE;) and that you need to concatenate using the ?||? the values selected from the database.

6. What SQLPlus command is used to format output from a select

This is best done with the COLUMN command.

Page 81: C Questions

7. You want to group the following set of select returns, what can you group on

Max(sum_of_cost), min(sum_of_cost), count(item_no), item_no The only column that can be grouped on is the "item_no" column, the rest have aggregate functions associated with them.

8. What special Oracle feature allows you to specify how the cost based system treats a SQL statement

The COST based system allows the use of HINTs to control the optimizer path selection. If they can give some example hints such as FIRST ROWS, ALL ROWS, USING INDEX, STAR, even better.

9. You want to determine the location of identical rows in a table before attempting to place a unique index on the table, how can this be done

Oracle tables always have one guaranteed unique column, the rowid column. If you use a min/max function against your rowid and then select against the proposed primary key you can squeeze out the rowids of the duplicate rows pretty quick. For example:select rowid from emp ewhere e.rowid > (select min(x.rowid)from emp xwhere x.emp_no = e.emp_no);In the situation where multiple columns make up the proposed key, they must all be used in the where clause.

Page 82: C Questions

10. What is a Cartesian product

A Cartesian product is the result of an unrestricted join of two or more tables. The result set of a three table Cartesian product will have x * y * z number of rows where x, y, z correspond to the number of rows in each table involved in the join.

11. You are joining a local and a remote table, the network manager complains about the traffic involved, how can you reduce the network traffic

Push the processing of the remote data to the remote instance by using a view to pre-select the information for the join. This will result in only the data required for the join being sent across.

12. What is the default ordering of an ORDER BY clause in a SELECT statement

Ascending

13. What is tkprof and how is it used

The tkprof tool is a tuning tool used to determine cpu and execution times for SQL statements. You use it by first setting timed_statistics to true in the initialization file and then turning on tracing for either the entire database via the sql_trace parameter or for the session using the ALTER SESSION command. Once the trace file is generated you run the tkprof tool against the trace file and then look at the output from the tkprof tool. This can also be used to generate explain plan output.

13.What is explain plan and how is it used

Page 83: C Questions

The EXPLAIN PLAN command is a tool to tune SQL statements. To use it you must have an explain_table generated in the user you are running the explain plan for. This is created using the utlxplan.sql script. Once the explain plan table exists you run the explain plan command giving as its argument the SQL statement to be explained. The explain_plan table is then queried to see the execution plan of the statement. Explain plans can also be run using tkprof.

14. How do you set the number of lines on a page of output? The width

The SET command in SQLPLUS is used to control the number of lines generated per page and the width of those lines, for example SET PAGESIZE 60 LINESIZE 80 will generate reports that are 60 lines long with a line width of 80 characters. The PAGESIZE and LINESIZE options can be shortened to PAGES and LINES.

15. How do you prevent output from coming to the screen

The SET option TERMOUT controls output to the screen. Setting TERMOUT OFF turns off screen output. This option can be shortened to TERM.

16. How do you prevent Oracle from giving you informational messages during and after a SQL statement execution

The SET options FEEDBACK and VERIFY can be set to OFF.

17. How do you generate file output from SQL

Page 84: C Questions

By use of the SPOOL command

1. A tablespace has a table with 30 extents in it. Is this bad? Why or why not.

Multiple extents in and of themselves aren?t bad. However if you also have chained rows this can hurt performance.

2. How do you set up tablespaces during an Oracle installation?

You should always attempt to use the Oracle Flexible Architecture standard or another partitioning scheme to ensure proper separation of SYSTEM, ROLLBACK, REDO LOG, DATA, TEMPORARY and INDEX segments.

3. You see multiple fragments in the SYSTEM tablespace, what should you check first?

Ensure that users don?t have the SYSTEM tablespace as their TEMPORARY or DEFAULT tablespace assignment by checking the DBA_USERS view.

4. What are some indications that you need to increase the SHARED_POOL_SIZE parameter?

Poor data dictionary or library cache hit ratios, getting error ORA-04031. Another indication is steadily decreasing performance with all other tuning parameters the same.

5. What is the general guideline for sizing db_block_size and db_multi_block_read for an application that does many full table scans?

Page 85: C Questions

Oracle almost always reads in 64k chunks. The two should have a product equal to 64 or a multiple of 64.

6. What is the fastest query method for a table

Fetch by rowid

7. Explain the use of TKPROF? What initialization parameter should be turned on to get full TKPROF output?

The tkprof tool is a tuning tool used to determine cpu and execution times for SQL statements. You use it by first setting timed_statistics to true in the initialization file and then turning on tracing for either the entire database via the sql_trace parameter or for the session using the ALTER SESSION command. Once the trace file is generated you run the tkprof tool against the trace file and then look at the output from the tkprof tool. This can also be used to generate explain plan output.

8. When looking at v$sysstat you see that sorts (disk) is high. Is this bad or good? If bad -How do you correct it?

If you get excessive disk sorts this is bad. This indicates you need to tune the sort area parameters in the initialization files. The major sort are parameter is the SORT_AREA_SIZe parameter.

9. When should you increase copy latches? What parameters control copy latches

When you get excessive contention for the copy latches as shown by the "redo copy" latch hit ratio.

Page 86: C Questions

You can increase copy latches via the initialization parameter LOG_SIMULTANEOUS_COPIES to twice the number of CPUs on your system.

10. Where can you get a list of all initialization parameters for your instance? How about an indication if they are default settings or have been changed

You can look in the init.ora file for an indication of manually set parameters. For all parameters, their value and whether or not the current value is the default value, look in the v$parameter view.

11. Describe hit ratio as it pertains to the database buffers. What is the difference between instantaneous and cumulative hit ratio and which should be used for tuning

The hit ratio is a measure of how many times the database was able to read a value from the buffers verses how many times it had to re-read a data value from the disks. A value greater than 80-90% is good, less could indicate problems. If you simply take the ratio of existing parameters this will be a cumulative value since the database started. If you do a comparison between pairs of readings based on some arbitrary time span, this is the instantaneous ratio for that time span. Generally speaking an instantaneous reading gives more valuable data since it will tell you what your instance is doing for the time it was generated over.

12. Discuss row chaining, how does it happen? How can you reduce it? How do you correct it

Page 87: C Questions

Row chaining occurs when a VARCHAR2 value is updated and the length of the new value is longer than the old value and won?t fit in the remaining block space. This results in the row chaining to another block. It can be reduced by setting the storage parameters on the table to appropriate values. It can be corrected by export and import of the effected table.

13. When looking at the estat events report you see that you are getting busy buffer waits. Is this bad? How can you find what is causing it

Buffer busy waits could indicate contention in redo, rollback or data blocks. You need to check the v$waitstat view to see what areas are causing the problem. The value of the "count" column tells where the problem is, the "class" column tells you with what. UNDO is rollback segments, DATA is data base buffers.

14. If you see contention for library caches how can you fix it

Increase the size of the shared pool.

15. If you see statistics that deal with "undo" what are they really talking about

Rollback segments and associated structures.

16. If a tablespace has a default pctincrease of zero what will this cause (in relationship to the smon process)

The SMON process won?t automatically coalesce its free space fragments.

Page 88: C Questions

17. If a tablespace shows excessive fragmentation what are some methods to defragment the tablespace? (7.1,7.2 and 7.3 only)

In Oracle 7.0 to 7.2 The use of the 'alter session set events 'immediate trace name coalesce level ts#';? command is the easiest way to defragment contiguous free space fragmentation. The ts# parameter corresponds to the ts# value found in the ts$ SYS table. In version 7.3 the ?alter tablespace coalesce;? is best. If the free space isn?t contiguous then export, drop and import of the tablespace contents may be the only way to reclaim non-contiguous free space.

18. How can you tell if a tablespace has excessive fragmentation

If a select against the dba_free_space table shows that the count of a tablespaces extents is greater than the count of its data files, then it is fragmented.

19. You see the following on a status report:

redo log space requests 23, redo log space wait time 0 Is this something to worry about? What if redo log space wait time is high? How can you fix this Since the wait time is zero, no. If the wait time was high it might indicate a need for more or larger redo logs.

20. What can cause a high value for recursive calls? How can this be fixed

A high value for recursive calls is cause by improper cursor usage, excessive dynamic space management actions, and or excessive statement re-parses. You

Page 89: C Questions

need to determine the cause and correct it By either relinking applications to hold cursors, use proper space management techniques (proper storage and sizing) or ensure repeat queries are placed in packages for proper reuse.

21. If you see a pin hit ratio of less than 0.8 in the estat library cache report is this a problem? If so, how do you fix it

This indicate that the shared pool may be too small. Increase the shared pool size.

22. If you see the value for reloads is high in the estat library cache report is this a matter for concern

Yes, you should strive for zero reloads if possible. If you see excessive reloads then increase the size of the shared pool.

23. You look at the dba_rollback_segs view and see that there is a large number of shrinks and they are of relatively small size, is this a problem? How can it be fixed if it is a problem

A large number of small shrinks indicates a need to increase the size of the rollback segment extents. Ideally you should have no shrinks or a small number of large shrinks. To fix this just increase the size of the extents and adjust optimal accordingly.

24. You look at the dba_rollback_segs view and see that you have a large number of wraps is this a problem

Page 90: C Questions

A large number of wraps indicates that your extent size for your rollback segments are probably too small. Increase the size of your extents to reduce the number of wraps. You can look at the average transaction size in the same view to get the information on transaction size.

25. In a system with an average of 40 concurrent users you get the following from a query on rollback extents:

ROLLBACK CUR EXTENTS --------------------- -------------------------- R01 11 R02 8R03 12R04 9SYSTEM 4

26. You have room for each to grow by 20 more extents each. Is there a problem? Should you take any action

No there is not a problem. You have 40 extents showing and an average of 40 concurrent users. Since there is plenty of room to grow no action is needed.

27. You see multiple extents in the temporary tablespace. Is this a problem

As long as they are all the same size this isn?t a problem. In fact, it can even improve performance since Oracle won?t have to create a new extent when a user needs one.

28. Define OFA.

Page 91: C Questions

OFA stands for Optimal Flexible Architecture. It is a method of placing directories and files in an Oracle system so that you get the maximum flexibility for future tuning and file placement.

29. How do you set up your tablespace on installation

The answer here should show an understanding of separation of redo and rollback, data and indexes and isolation os SYSTEM tables from other tables. An example would be to specify that at least 7 disks should be used for an Oracle installation so that you can place SYSTEM tablespace on one, redo logs on two (mirrored redo logs) the TEMPORARY tablespace on another, ROLLBACK tablespace on another and still have two for DATA and INDEXES. They should indicate how they will handle archive logs and exports as well. As long as they have a logical plan for combining or further separation more or less disks can be specified.

30. What should be done prior to installing Oracle (for the OS and the disks)

adjust kernel parameters or OS tuning parameters in accordance with installation guide. Be sure enough contiguous disk space is available.

31. You have installed Oracle and you are now setting up the actual instance. You have been waiting an hour for the initialization script to finish, what should you check first to determine if there is a problem

Page 92: C Questions

Check to make sure that the archiver isn?t stuck. If archive logging is turned on during install a large number of logs will be created. This can fill up your archive log destination causing Oracle to stop to wait for more space.

32. When configuring SQLNET on the server what files must be set up

INITIALIZATION file, TNSNAMES.ORA file, SQLNET.ORA file

33. When configuring SQLNET on the client what files need to be set up

SQLNET.ORA, TNSNAMES.ORA

34. What must be installed with ODBC on the client in order for it to work with Oracle

SQLNET and PROTOCOL (for example: TCPIP adapter) layers of the transport programs.

35. You have just started a new instance with a large SGA on a busy existing server. Performance is terrible, what should you check for

The first thing to check with a large SGA is that it isn?t being swapped out.

36. What OS user should be used for the first part of an Oracle installation (on UNIX)

You must use root first.

37. When should the default values for Oracle initialization parameters be used as is

Page 93: C Questions

Never

38. How many control files should you have? Where should they be located

At least 2 on separate disk spindles. Be sure they say on separate disks, not just file systems.

39. How many redo logs should you have and how should they be configured for maximum recoverability

You should have at least three groups of two redo logs with the two logs each on a separate disk spindle (mirrored by Oracle). The redo logs should not be on raw devices on UNIX if it can be avoided.

41. Describe third normal form

Something like: In third normal form all attributes in an entity are related to the primary key and only to the primary key

42. Is the following statement true or false:

"All relational databases must be in third normal form" False. While 3NF is good for logical design most databases, if they have more than just a few tables, will not perform well using full 3NF. Usually some entities will be denormalized in the logical to physical transfer process.

43. What is an ERD

An ERD is an Entity-Relationship-Diagram. It is used to show the entities and relationships for a database logical model.

Page 94: C Questions

44. Why are recursive relationships bad? How do you resolve them

A recursive relationship (one where a table relates to itself) is bad when it is a hard relationship (i.e. neither side is a "may" both are "must") as this can result in it not being possible to put in a top or perhaps a bottom of the table (for example in the EMPLOYEE table you couldn?t put in the PRESIDENT of the company because he has no boss, or the junior janitor because he has no subordinates). These type of relationships are usually resolved by adding a small intersection entity.

45. What does a hard one-to-one relationship mean (one where the relationship on both ends is "must")

Expected answer: This means the two entities should probably be made into one entity.

46. How should a many-to-many relationship be handled

By adding an intersection entity table

47. What is an artificial (derived) primary key? When should an artificial (or derived) primary key be used

A derived key comes from a sequence. Usually it is used when a concatenated key becomes too cumbersome to use as a foreign key.

When should you consider denormalization

Page 95: C Questions

Whenever performance analysis indicates it would be beneficial to do so without compromising data integrity.

49. How can you determine if an Oracle instance is up from the operating system level

There are several base Oracle processes that will be running on multi-user operating systems, these will be smon, pmon, dbwr and lgwr. Any answer that has them using their operating system process showing feature to check for these is acceptable. For example, on UNIX a ps -ef|grep dbwr will show what instances are up.

50. Users from the PC clients are getting messages indicating :

ORA-06114: (Cnct err, can't get err txt. See Servr Msgs & Codes Manual)

51. Users from the PC clients are getting the following error stack:

ERROR: ORA-01034: ORACLE not availableORA-07318: smsget: open error when opening sgadef.dbf file.HP-UX Error: 2: No such file or directory

52. How can you determine if the SQLNET process is running for SQLNET V1? How about V2

For SQLNET V1 check for the existence of the orasrv process. You can use the command "tcpctl status" to get a full status of the V1 TCPIP server, other protocols have similar command formats. For SQLNET V2 check for the presence of the LISTENER process(s) or you can issue the command "lsnrctl status".

53. What file will give you Oracle instance status information? Where is it located

The alert.ora log. It is located in the directory specified by the background_dump_dest parameter in the v$parameter table.

54.Users aren?t being allowed on the system. The following message is received: ORA-00257 archiver is stuck. Connect internal only, until freedWhat is the problem?

The archive destination is probably full, backup the archive logs and remove them and the archiver will re-start.

Page 96: C Questions

55. Where would you look to find out if a redo log was corrupted assuming you are using Oracle mirrored redo logs

There is no message that comes to the SQLDBA or SRVMGR programs during startup in this situation, you must check the alert.log file for this information.

56. You attempt to add a datafile and get:ORA-01118: cannot add anymore datafiles: limit of 40 exceededWhat is the problem and how can you fix it

When the database was created the db_files parameter in the initialization file was set to 40. You can shutdown and reset this to a higher value, up to the value of MAX_DATAFILES as specified at database creation. If the MAX_DATAFILES is set to low, you will have to rebuild the control file to increase it before proceeding.

57. You look at your fragmentation report and see that smon hasn?t coalesced any of you tablespaces, even though you know several have large chunks of contiguous free extents. What is the problem

Check the dba_tablespaces view for the value of pct_increase for the tablespaces. If pct_increase is zero, smon will not coalesce their free space.

58. Your users get the following error: ORA-00055 maximum number of DML locks exceededWhat is the problem and how do you fix it

The number of DML Locks is set by the initialization parameter DML_LOCKS. If this value is set to low (which it is by default) you will get this error. Increase the value of DML_LOCKS. If you are sure that this is just a temporary problem, you can have them wait and then try again later and the error should clear.

1. What is a CO-RELATED SUBQUERY

A CO-RELATED SUBQUERY is one that has a correlation name as table or view designator in the FROM clause of the outer query and the same correlation name as a qualifier of a search condition in the WHERE clause of the subquery.egSELECT field1 from table1 XWHERE field2>(select avg(field2) from table1 Y

Page 97: C Questions

wherefield1=X.field1);(The subquery in a correlated subquery is revaluated for every row of the table or view named in the outer query.)

6. What are various joins used while writing SUBQUERIES

Self join-Its a join foreign key of a table references the same table.Outer Join--Its a join condition used where One can query all the rows of one of the tables in the join condition even though they don't satisfy the join condition.Equi-join--Its a join condition that retrieves rows from one or more tables in which one or more columns in one table are equal to one or more columns in the second table.

7. What are various constraints used in SQL

NULLNOT NULLCHECKDEFAULT

8. What are different Oracle database objects

TABLESVIEWSINDEXESSYNONYMSSEQUENCESTABLESPACES etc

9. What is difference between Rename and Alias

Rename is a permanent name given to a table or column whereas Alias is a temporary name given to a table or column which do not exist once the SQL statement is executed.

10. What is a view

A view is stored procedure based on one or more tables, its a virtual table.

11. What are various privileges that a user can grant to another user

Page 98: C Questions

SELECTCONNECTRESOURCE

12. What is difference between UNIQUE and PRIMARY KEY constraints

A table can have only one PRIMARY KEY whereas there can be any number of UNIQUE keys. The columns that compose PK are automatically define NOT NULL, whereas a column that compose a UNIQUE is not automatically defined to be mandatory must also specify the column is NOT NULL.

13. Can a primary key contain more than one columns

Yes

14. How you will avoid duplicating records in a query

By using DISTINCT

15. What is difference between SQL and SQL*PLUS

SQL*PLUS is a command line tool where as SQL and PL/SQL language interface and reporting tool. Its a command line tool that allows user to type SQL commands to be executed directly against an Oracle database. SQL is a language used to query the relational database(DML,DCL,DDL). SQL*PLUS commands are used to format query result, Set options, Edit SQL commands and PL/SQL.

16. Which datatype is used for storing graphics and images

LONG RAW data type is used for storing BLOB's (binary large objects).

17. How will you delete duplicating rows from a base table

DELETE FROM table_name A WHERE rowid>(SELECT min(rowid) from table_name B where B.table_no=A.table_no);CREATE TABLE new_table AS SELECT DISTINCT * FROM old_table;DROP old_table RENAME new_table TO old_table DELETE FROM table_name A WHERE rowid NOT IN (SELECT MAX(ROWID) FROM table_name GROUP BY column_name)

18. What is difference between SUBSTR and INSTR

Page 99: C Questions

SUBSTR returns a specified portion of a string eg SUBSTR('BCDEF',4) output BCDE INSTR provides character position in which a pattern is found in a string. eg INSTR('ABC-DC-F','-',2) output 7 (2nd occurence of '-')

19. There is a string '120000 12 0 .125' ,how you will find the position of the decimal place

INSTR('120000 12 0 .125',1,'.') output 13

20. There is a '%' sign in one field of a column. What will be the query to find it.

'\' Should be used before '%'.

21. When you use WHERE clause and when you use HAVING clause

HAVING clause is used when you want to specify a condition for a group function and it is written after GROUP BY clause The WHERE clause is used when you want to specify a condition for columns, single row functions except group functions and it is written before GROUP BY clause if it is used.

22. Which is more faster - IN or EXISTS

EXISTS is more faster than IN because EXISTS returns a Boolean value whereas IN returns a value.

23. What is a OUTER JOIN

Outer Join--Its a join condition used where you can query all the rows of one of the tables in the join condition even though they dont satisfy the join condition.

24. How you will avoid your query from using indexes

SELECT * FROM emp Where emp_no+' '=12345; i.e you have to concatenate the column name with space within codes in the where condition. SELECT /*+ FULL(a) */ ename, emp_no from emp where emp_no=1234; i.e using HINTS

25. What is a pseudo column. Give some examples

It is a column that is not an actual column in the table. eg USER, UID, SYSDATE, ROWNUM, ROWID, NULL, AND LEVEL. Suppose customer

Page 100: C Questions

table is there having different columns like customer no, payments.What will be the query to select top three max payments. SELECT customer_no, payments from customer C1 WHERE 3<=(SELECT COUNT(*) from customer C2 WHERE C1.payment <= C2.payment)

26. What is the purpose of a cluster.

Oracle does not allow a user to specifically locate tables, since that is a part of the function of the RDBMS. However, for the purpose of increasing performance, oracle allows a developer to create a CLUSTER. A CLUSTER provides a means for storing data from different tables together for faster retrieval than if the table placement were left to the RDBMS.

27.What is a cursor.

Oracle uses work area to execute SQL statements and store processing information PL/SQL construct called a cursor lets you name a work area and access its stored information A cursor is a mechanism used to fetch more than one row in a Pl/SQl block.

28. Difference between an implicit & an explicit cursor.

PL/SQL declares a cursor implicitly for all SQL data manipulation statements, including quries that return only one row. However,queries that return more than one row you must declare an explicit cursor or use a cursor FOR loop. Explicit cursor is a cursor in which the cursor name is explicitly assigned to a SELECT statement via the CURSOR...IS statement. An implicit cursor is used for all SQL statements Declare, Open, Fetch, Close. An explicit cursors are used to process multirow SELECT statements An implicit cursor is used to process INSERT, UPDATE, DELETE and single row SELECT. .INTO statements.

29. What are cursor attributes

%ROWCOUNT%NOTFOUND%FOUND%ISOPEN

30. What is a cursor for loop.

Page 101: C Questions

Cursor For Loop is a loop where oracle implicitly declares a loop variable, the loop index that of the same record type as the cursor's record.

31. Difference between NO DATA FOUND and %NOTFOUND

NO DATA FOUND is an exception raised only for the SELECT....INTO statements when the where clause of the querydoes not match any rows. When the where clause of the explicit cursor does not match any rows the %NOTFOUND attribute is set to TRUE instead.

32. What a SELECT FOR UPDATE cursor represent.

SELECT......FROM......FOR......UPDATE[OF column-reference][NOWAIT] The processing done in a fetch loop modifies the rows that have been retrieved by the cursor. A convenient way of modifying the rows is done by a method with two parts: the FOR UPDATE clause in the cursor declaration, WHERE CURRENT OF CLAUSE in an UPDATE or declaration statement.

42. What is use of a cursor variable? How it is defined.

A cursor variable is associated with different statements at run time, which can hold different values at run time. Static cursors can only be associated with one run time query. A cursor variable is reference type(like a pointer in C). Declaring a cursor variable: TYPE type_name IS REF CURSOR RETURN return_type type_name is the name of the reference type,return_type is a record type indicating the types of the select list that will eventually be returned by the cursor variable.

43. What should be the return type for a cursor variable.Can we use a scalar data type as return type.

The return type for a cursor must be a record type.It can be declared explicitly as a user-defined or %ROWTYPE can be used. eg TYPE t_studentsref IS REF CURSOR RETURN students%ROWTYPE

44. How you open and close a cursor variable.Why it is required.

OPEN cursor variable FOR SELECT...Statement CLOSE cursor variable In order to associate a cursor variable with a particular SELECT statement OPEN syntax is used.In order to free the resources used for the query CLOSE statement is used.

45. How you were passing cursor variables in PL/SQL 2.2.

Page 102: C Questions

In PL/SQL 2.2 cursor variables cannot be declared in a package.This is because the storage for a cursor variable has to be allocated using Pro*C or OCI with version 2.2,the only means of passing a cursor variable to a PL/SQL block is via bind variable or a procedure parameter.

46. Can cursor variables be stored in PL/SQL tables.If yes how.If not why.

No, a cursor variable points a row which cannot be stored in a two-dimensional PL/SQL table.

47. Difference between procedure and function.

Functions are named PL/SQL blocks that return a value and can be called with arguments procedure a named block that can be called with parameter. A procedure all is a PL/SQL statement by itself, while a Function call is called as part of an expression.

48. What are different modes of parameters used in functions and procedures.

INOUTINOUT

49. What is difference between a formal and an actual parameter

The variables declared in the procedure and which are passed, as arguments are called actual, the parameters in the procedure declaration. Actual parameters contain the values that are passed to a procedure and receive results. Formal parameters are the placeholders for the values of actual parameters

50. Can the default values be assigned to actual parameters.

Yes

51. Can a function take OUT parameters.If not why.

No.A function has to return a value,an OUT parameter cannot return a value.

52. What is syntax for dropping a procedure and a function .Are these operations possible.

Page 103: C Questions

Drop Procedure procedure_name Drop Function function_name

56. What are ORACLE PRECOMPILERS.

Using ORACLE PRECOMPILERS ,SQL statements and PL/SQL blocks can be contained inside 3GL programs written in C,C++,COBOL,PASCAL, FORTRAN,PL/1 AND ADA. The Precompilers are known as Pro*C,Pro*Cobol,... This form of PL/SQL is known as embedded pl/sql,the language in which pl/sql is embedded is known as the host language. The prcompiler translates the embedded SQL and pl/sql ststements into calls to the precompiler runtime library.The output must be compiled and linked with this library to creater an executable.

57. What is OCI. What are its uses.

Oracle Call Interface is a method of accesing database from a 3GL program. Uses--No precompiler is required,PL/SQL blocks are executed like other DML statements. The OCI library provides-functions to parse SQL statemets-bind input variables-bind output variables-execute statements-fetch the results

64. Difference between database triggers and form triggers.

a) Data base trigger(DBT) fires when a DML operation is performed on a data base table.Form trigger(FT) Fires when user presses a key or navigates between fields on the screenb) Can be row level or statement level No distinction between row level and statement level.c) Can manipulate data stored in Oracle tables via SQL Can manipulate data in Oracle tables as well as variables in forms.d) Can be fired from any session executing the triggering DML statements. Can be fired only from the form that define the trigger.e) Can cause other database triggers to fire.Can cause other database triggers to fire,but not other form triggers.

65. What is an UTL_FILE.What are different procedures and functions associated

with it. UTL_FILE is a package that adds the ability to read and write to operating system files Procedures associated with it are FCLOSE, FCLOSE_ALL and 5 procedures to output data to a file PUT, PUT_LINE, NEW_LINE, PUTF, FFLUSH.PUT, FFLUSH.PUT_LINE,FFLUSH.NEW_LINE. Functions associated with it are FOPEN, ISOPEN.

Page 104: C Questions

66. Can you use a commit statement within a database trigger.

No

67. What is the maximum buffer size that can be specified using the DBMS_OUTPUT.ENABLE function?

1,000,000

Oracle Interview Questions

1. How would you determine the time zone under which a database was operating? 2. Explain the use of setting GLOBAL_NAMES equal to TRUE. 3. What command would you use to encrypt a PL/SQL application?4. Explain the difference between a FUNCTION, PROCEDURE and PACKAGE. 5. Explain the use of table functions. 6. Name three advisory statistics you can collect. 7. Where in the Oracle directory tree structure are audit traces placed? 8. Explain materialized views and how they are used. 9. When a user process fails, what background process cleans up after it? 10. What background process refreshes materialized views? 11. How would you determine what sessions are connected and what resources they are waiting for? 12. Describe what redo logs are. 13. How would you force a log switch?14. Give two methods you could use to determine what DDL changes have been made. 15. What does coalescing a tablespace do? 16. What is the difference between a TEMPORARY tablespace and a PERMANENT tablespace? 17. Name a tablespace automatically created when you create a database. 18. When creating a user, what permissions must you grant to allow them to connect to the database? 19. How do you add a data file to a tablespace? 20. How do you resize a data file? 21. What view would you use to look at the size of a data file? 22. What view would you use to determine free space in a tablespace?23. How would you determine who has added a row to a table? 24. How can you rebuild an index?

Page 105: C Questions

25. Explain what partitioning is and what its benefit is. 26. You have just compiled a PL/SQL package but got errors, how would you view the errors? 27. How can you gather statistics on a table? 28. How can you enable a trace for a session? 29. What is the difference between the SQL*Loader and IMPORT utilities? 30. Name two files used for network connection to a database.

Relational Database Management System Frequently Asked Questions

1. What is database?

A database is a logically coherent collection of data with some inherent meaning, representing some aspect of real world and which is designed, built and populated with data for a specific purpose.

2. What is DBMS?

It is a collection of programs that enables user to create and maintain a database. In other words it is general-purpose software that provides the users with the processes of defining, constructing and manipulating the database for various applications.

3. What is a Database system?

The database and DBMS software together is called as Database system.

Page 106: C Questions

4. Advantages of DBMS?

Redundancy is controlled.Unauthorised access is restricted.Providing multiple user interfaces.Enforcing integrity constraints.Providing backup and recovery.

5. Disadvantage in File Processing System?

Data redundancy & inconsistency.Difficult in accessing data.Data isolation.Data integrity.Concurrent access is not possible. Security Problems.

6. Describe the three levels of data abstraction?

The are three levels of abstraction:Physical level: The lowest level of abstraction describes how data are stored.Logical level: The next higher level of abstraction, describes what data are stored in database and what relationship among those data. View level: The highest level of abstraction describes only part of entire database.

7. Define the "integrity rules"

There are two Integrity rules.Entity Integrity: States that “Primary key cannot have NULL value”Referential Integrity: States that “Foreign Key can be either a NULL value or should be Primary Key value of other relation.

8. What is extension and intension?

Extension - It is the number of tuples present in a table at any instance. This is time dependent.Intension - It is a constant value that gives the name, structure of table and the constraints laid on it.

9. What is System R? What are its two major subsystems?

Page 107: C Questions

System R was designed and developed over a period of 1974-79 at IBM San Jose Research Center. It is a prototype and its purpose was to demonstrate that it is possible to build a Relational System that can be used in a real life environment to solve real life problems, with performance at least comparable to that of existing system.

Its two subsystems are Research Storage System Relational Data System.

10. How is the data structure of System R different from the relational structure?

Unlike Relational systems in System R Domains are not supportedEnforcement of candidate key uniqueness is optionalEnforcement of entity integrity is optionalReferential integrity is not enforced

11. What is Data Independence?

Data independence means that “the application is independent of the storage structure and access strategy of data”. In other words, The ability to modify the schema definition in one level should not affect the schema definition in the next higher level.Two types of Data Independence:Physical Data Independence: Modification in physical level should not affect the logical level.Logical Data Independence: Modification in logical level should affect the view level.NOTE: Logical Data Independence is more difficult to achieve

12. What is a view? How it is related to data independence?

A view may be thought of as a virtual table, that is, a table that does not really exist in its own right but is instead derived from one or more underlying base table. In other words, there is no stored file that direct represents the view instead a definition of view is stored in data dictionary. Growth and restructuring of base tables is not reflected in views. Thus the view can insulate users from the effects of restructuring and growth in the database. Hence accounts for logical data independence.

13. What is Data Model?

Page 108: C Questions

A collection of conceptual tools for describing data, data relationships data semantics and constraints.

14. What is E-R model?

This data model is based on real world that consists of basic objects called entities and of relationship among these objects. Entities are described in a database by a set of attributes.

15. What is Object Oriented model?

This model is based on collection of objects. An object contains values stored in instance variables with in the object. An object also contains bodies of code that operate on the object. These bodies of code are called methods. Objects that contain same types of values and the same methods are grouped together into classes.

16. What is an Entity?

It is a 'thing' in the real world with an independent existence.

17. What is an Entity type?

It is a collection (set) of entities that have same attributes.

18. What is an Entity set?

It is a collection of all entities of particular entity type in the database.

19. What is an Extension of entity type?

The collections of entities of a particular entity type are grouped together into an entity set.

20. What is Weak Entity set?

An entity set may not have sufficient attributes to form a primary key, and its primary key compromises of its partial key and primary key of its parent entity, then it is said to be Weak Entity set.

21.What is an attribute?

It is a particular property, which describes the entity.

22. What is a Relation Schema and a Relation?

Page 109: C Questions

A relation Schema denoted by R(A1, A2, …, An) is made up of the relation name R and the list of attributes Ai that it contains. A relation is defined as a set of tuples. Let r be the relation which contains set tuples (t1, t2, t3, ..., tn). Each tuple is an ordered list of n-values t=(v1,v2, ..., vn).

23. What is degree of a Relation?

It is the number of attribute of its relation schema.

24. What is Relationship?

It is an association among two or more entities.

25. What is Relationship set?

The collection (or set) of similar relationships.

26. What is Relationship type?

Relationship type defines a set of associations or a relationship set among a given set of entity types.

27. What is degree of Relationship type?

It is the number of entity type participating.

25. What is DDL (Data Definition Language)?

A data base schema is specifies by a set of definitions expressed by a special language called DDL.

26. What is VDL (View Definition Language)?

It specifies user views and their mappings to the conceptual schema.

27. What is SDL (Storage Definition Language)?

This language is to specify the internal schema. This language may specify the mapping between two schemas.

28. What is Data Storage - Definition Language?

The storage structures and access methods used by database system are specified by a set of definition in a special type of DDL called data storage-definition language.

Page 110: C Questions

29.What is DML (Data Manipulation Language)?

This language that enable user to access or manipulate data as organised by appropriate data model.Procedural DML or Low level: DML requires a user to specify what data are needed and how to get those data.Non-Procedural DML or High level: DML requires a user to specify what data are needed without specifying how to get those data.

31. What is DML Compiler?

It translates DML statements in a query language into low-level instruction that the query evaluation engine can understand.

32. What is Query evaluation engine?

It executes low-level instruction generated by compiler.

33. What is DDL Interpreter?

It interprets DDL statements and record them in tables containing metadata.

34. What is Record-at-a-time?

The Low level or Procedural DML can specify and retrieve each record from a set of records. This retrieve of a record is said to be Record-at-a-time.

35. What is Set-at-a-time or Set-oriented?

The High level or Non-procedural DML can specify and retrieve many records in a single DML statement. This retrieve of a record is said to be Set-at-a-time or Set-oriented.

36. What is Relational Algebra?

It is procedural query language. It consists of a set of operations that take one or two relations as input and produce a new relation.

37. What is Relational Calculus?

It is an applied predicate calculus specifically tailored for relational databases proposed by E.F. Codd. E.g. of languages based on it are DSL ALPHA, QUEL.

Page 111: C Questions

38. How does Tuple-oriented relational calculus differ from domain-oriented relational calculus

The tuple-oriented calculus uses a tuple variables i.e., variable whose only permitted values are tuples of that relation. E.g. QUEL The domain-oriented calculus has domain variables i.e., variables that range over the underlying domains instead of over relation. E.g. ILL, DEDUCE.

39. What is normalization?

It is a process of analysing the given relation schemas based on their Functional Dependencies (FDs) and primary key to achieve the propertiesMinimizing redundancyMinimizing insertion, deletion and update anomalies.

40. What is Functional Dependency?

A Functional dependency is denoted by X Y between two sets of attributes X and Y that are subsets of R specifies a constraint on the possible tuple that can form a relation state r of R. The constraint is for any two tuples t1 and t2 in r if t1[X] = t2[X] then they have t1[Y] = t2[Y]. This means the value of X component of a tuple uniquely determines the value of component Y.

41. When is a functional dependency F said to be minimal?

Every dependency in F has a single attribute for its right hand side.We cannot replace any dependency X A in F with a dependency Y A where Y is a proper subset of X and still have a set of dependency that is equivalent to F.We cannot remove any dependency from F and still have set of dependency that is equivalent to F.

42. What is Multivalued dependency?

Multivalued dependency denoted by X Y specified on relation schema R, where X and Y are both subsets of R, specifies the following constraint on any relation r of R: if two tuples t1 and t2 exist in r such that t1[X] = t2[X] then t3 and t4 should also exist in r with the following propertiest3[x] = t4[X] = t1[X] = t2[X]t3[Y] = t1[Y] and t4[Y] = t2[Y]t3[Z] = t2[Z] and t4[Z] = t1[Z] where [Z = (R-(X U Y)) ]

Page 112: C Questions

43. What is Lossless join property?

It guarantees that the spurious tuple generation does not occur with respect to relation schemas after decomposition.

44. What is 1 NF (Normal Form)?

The domain of attribute must include only atomic (simple, indivisible) values.

45. What is Fully Functional dependency?

It is based on concept of full functional dependency. A functional dependency X Y is full functional dependency if removal of any attribute A from X means that the dependency does not hold any more.

46. What is 2NF?

A relation schema R is in 2NF if it is in 1NF and every non-prime attribute A in R is fully functionally dependent on primary key.

47. What is 3NF?

A relation schema R is in 3NF if it is in 2NF and for every FD X A either of the following is trueX is a Super-key of R.A is a prime attribute of R.In other words, if every non prime attribute is non-transitively dependent on primary key.

48. What is BCNF (Boyce-Codd Normal Form)?

A relation schema R is in BCNF if it is in 3NF and satisfies an additional constraint that for every FD X A, X must be a candidate key.

49. What is 4NF?

A relation schema R is said to be in 4NF if for every Multivalued dependency X Y that holds over R, one of following is trueX is subset or equal to (or) XY = R.X is a super key.

50. What is 5NF?

Page 113: C Questions

A Relation schema R is said to be 5NF if for every join dependency {R1, R2, ..., Rn} that holds R, one the following is true Ri = R for some i.The join dependency is implied by the set of FD, over R in which the left side is key of R.

51. What is Domain-Key Normal Form?

A relation is said to be in DKNF if all constraints and dependencies that should hold on the the constraint can be enforced by simply enforcing the domain constraint and key constraint on the relation.

52. What are partial, alternate,, artificial, compound and natural key?

Partial Key:It is a set of attributes that can uniquely identify weak entities and that are related to same owner entity. It is sometime called as Discriminator.Alternate Key:All Candidate Keys excluding the Primary Key are known as Alternate Keys.Artificial Key:If no obvious key, either stand alone or compound is available, then the last resort is to simply create a key, by assigning a unique number to each record or occurrence. Then this is known as developing an artificial key.Compound Key:If no single data element uniquely identifies occurrences within a construct, then combining multiple elements to create a unique identifier for the construct is known as creating a compound key.Natural Key:When one of the data elements stored within a construct is utilized as the primary key, then it is called the natural key.

What are cursors?

Well cursors help us to do an operation on a set of data that we retreive by commands such as Select columns from table. For example : If we have duplicate records in a table we can remove it by declaring a cursor which would check the records during retreival one by one and remove rows which have duplicate values.

When do we use the UPDATE_STATISTICS command?

Page 114: C Questions

This command is basically used when we do a large processing of data. If we do a large amount of deletions any modification or Bulk Copy into the tables, we need to basically update the indexes to take these changes into account. UPDATE_STATISTICS updates the indexes on these tables accordingly.

Which TCP/IP port does SQL Server run on?

SQL Server runs on port 1433 but we can also change it for better security.

From where can you change the default port?

From the Network Utility TCP/IP properties –> Port number.both on client and the server.

Can you tell me the difference between DELETE & TRUNCATE commands?

Delete command removes the rows from a table based on the condition that we provide with a WHERE clause. Truncate will actually remove all the rows from a table and there will be no data in the table after we run the truncate command.

Can we use Truncate command on a table which is referenced by FOREIGN KEY?

No. We cannot use Truncate command on a table with Foreign Key because of referential integrity.

What is the use of DBCC commands?

DBCC stands for database consistency checker. We use these commands to check the consistency of the databases, i.e., maintenance, validation task and status checks.

Can you give me some DBCC command options?(Database consistency check)

DBCC CHECKDB - Ensures that tables in the db and the indexes are correctly linked.and DBCC CHECKALLOC - To check that all pages in a db are correctly allocated. DBCC SQLPERF - It gives report on current usage of transaction log in percentage. DBCC CHECKFILEGROUP - Checks all tables file group for any damage.

What command do we use to rename a db?

Page 115: C Questions

sp_renamedb ‘oldname’ , ‘newname’

Well sometimes sp_reanmedb may not work you know because if some one is using the db it will not accept this command so what do you think you can do in such cases?

In such cases we can first bring to db to single user using sp_dboptions and then we can rename that db and then we can rerun the sp_dboptions command to remove the single user mode.

What is the difference between a HAVING CLAUSE and a WHERE CLAUSE?

Having Clause is basically used only with the GROUP BY function in a query. WHERE Clause is applied to each row before they are part of the GROUP BY function in a query.

What do you mean by COLLATION?

Collation is basically the sort order. There are three types of sort order Dictionary case sensitive, Dictonary - case insensitive and Binary.

What is a Join in SQL Server?

Join actually puts data from two or more tables into a single result set.

Can you explain the types of Joins that we can have with Sql Server?

There are three types of joins: Inner Join, Outer Join, Cross Join

When do you use SQL Profiler?

SQL Profiler utility allows us to basically track connections to the SQL Server and also determine activities such as which SQL Scripts are running, failed jobs etc..

What is a Linked Server?

Linked Servers is a concept in SQL Server by which we can add other SQL Server to a Group and query both the SQL Server dbs using T-SQL Statements.

Can you link only other SQL Servers or any database servers such as Oracle?

Page 116: C Questions

We can link any server provided we have the OLE-DB provider from Microsoft to allow a link. For Oracle we have a OLE-DB provider for oracle that microsoft provides to add it as a linked server to the sql server group.

Which stored procedure will you be running to add a linked server?

sp_addlinkedserver, sp_addlinkedsrvlogin

What are the OS services that the SQL Server installation adds?

MS SQL SERVER SERVICE, SQL AGENT SERVICE, DTC (Distribution transac co-ordinator)

Can you explain the role of each service?

SQL SERVER - is for running the databases SQL AGENT - is for automation such as Jobs, DB Maintanance, Backups DTC - Is for linking and connecting to other SQL Servers

How do you troubleshoot SQL Server if its running very slow?

First check the processor and memory usage to see that processor is not above 80% utilization and memory not above 40-45% utilization then check the disk utilization using Performance Monitor, Secondly, use SQL Profiler to check for the users and current SQL activities and jobs running which might be a problem. Third would be to run UPDATE_STATISTICS command to update the indexes

Lets say due to N/W or Security issues client is not able to connect to server or vice versa. How do you troubleshoot?

First I will look to ensure that port settings are proper on server and client Network utility for connections. ODBC is properly configured at client end for connection ——Makepipe & readpipe are utilities to check for connection. Makepipe is run on Server and readpipe on client to check for any connection issues.

What are the authentication modes in SQL Server?

Windows mode and mixed mode (SQL & Windows).

Where do you think the users names and passwords will be stored in sql server?

Page 117: C Questions

They get stored in master db in the sysxlogins table.

What is log shipping? Can we do logshipping with SQL Server 7.0

Logshipping is a new feature of SQL Server 2000. We should have two SQL Server - Enterprise Editions. From Enterprise Manager we can configure the logshipping. In logshipping the transactional log file from one server is automatically updated into the backup database on the other server. If one server fails, the other server will have the same db and we can use this as the DR (disaster recovery) plan.

Let us say the SQL Server crashed and you are rebuilding the databases including the master database what procedure to you follow?

For restoring the master db we have to stop the SQL Server first and then from command line we can type SQLSERVER .m which will basically bring it into the maintenance mode after which we can restore the master db.

Let us say master db itself has no backup. Now you have to rebuild the db so what kind of action do you take?

(I am not sure- but I think we have a command to do it).

What is BCP? When do we use it?

BulkCopy is a tool used to copy huge amount of data from tables and views. But it won’t copy the structures of the same.

What should we do to copy the tables, schema and views from one SQL Server to another?

We have to write some DTS packages for it.

What’s the difference between a primary key and a unique key?

Both primary key and unique enforce uniqueness of the column on which they are defined. But by default primary key creates a clustered index on the column, where are unique creates a nonclustered index by default. Another major difference is that, primary key doesn’t allow NULLs, but unique key allows one NULL only.

Write a SQL Query to find first Week Day of month?

Page 118: C Questions

SELECT DATENAME(dw, DATEADD(dd, - DATEPART(dd, GETDATE()) + 1, GETDATE())) AS FirstDay

How to find 6th highest salary from Employee table

SELECT TOP 1 salary FROM (SELECT DISTINCT TOP 6 salary FROM employee ORDER BY salary DESC) a ORDER BY salary

What is a join and List different types of joins.

Joins are used in queries to explain how different tables are related. Joins also let you select data from a table depending upon data from another table. Types of joins: INNER JOINs, OUTER JOINs, CROSS JOINs. OUTER JOINs are further classified as LEFT OUTER JOINS, RIGHT OUTER JOINS and FULL OUTER JOINS.

How can I enforce to use particular index?

You can use index hint (index=index_name) after the table name. SELECT au_lname FROM authors (index=aunmind)

What is sorting and what is the difference between sorting and clustered indexes?

The ORDER BY clause sorts query results by one or more columns up to 8,060 bytes. This will happen by the time when we retrieve data from database. Clustered indexes physically sorting data, while inserting/updating the table.

What are the differences between UNION and JOINS?

A join selects columns from 2 or more tables. A union selects rows.

What is the Referential Integrity?

Referential integrity refers to the consistency that must be maintained between primary and foreign keys, i.e. every foreign key value must have a corresponding primary key value

What is the row size in SQL Server 2000?

8060 bytes.

How to determine the service pack currently installed on SQL Server?

Page 119: C Questions

The global variable @@Version stores the build number of the sqlservr.exe, which is used to determine the service pack installed. eg: Microsoft SQL Server 2000 - 8.00.760 (Intel X86) Dec 17 2002 14:22:05 Copyright (c) 1988-2003 Microsoft Corporation Enterprise Edition on Windows NT 5.0 (Build 2195: Service Pack 3)

What is the purpose of UPDATE STATISTICS?

Updates information about the distribution of key values for one or more statistics groups (collections) in the specified table or indexed view.

What is the use of SCOPE_IDENTITY() function?

Returns the most recently created identity value for the tables in the current execution scope.

What are the different ways of moving data/databases between servers and databases in SQL Server?

There are lots of options available, you have to choose your option depending upon your requirements. Some of the options you have are: BACKUP/RESTORE, detaching and attaching databases, replication, DTS, BCP, logshipping, INSERT...SELECT, SELECT...INTO, creating INSERT scripts to generate data.

How do you transfer data from text file to database (other than DTS)?

Using the BCP (Bulk Copy Program) utility.

What's the difference between DELETE TABLE and TRUNCATE TABLE commands?

DELETE TABLE is a logged operation, so the deletion of each row gets logged in the transaction log, which makes it slow. TRUNCATE TABLE also deletes all the rows in a table, but it won't log the deletion of each row, instead it logs the deallocation of the data pages of the table, which makes it faster. Of course, TRUNCATE TABLE can be rolled back.

What is a deadlock?

Deadlock is a situation when two processes, each having a lock on one piece of data, attempt to acquire a lock on the other's piece. Each process would wait indefinitely for the other to release the lock, unless

Page 120: C Questions

one of the user processes is terminated. SQL Server detects deadlocks and terminates one user's process.

What is a LiveLock?

A livelock is one, where a request for an exclusive lock is repeatedly denied because a series of overlapping shared locks keeps interfering. SQL Server detects the situation after four denials and refuses further shared locks. A livelock also occurs when read transactions monopolize a table or page, forcing a write transaction to wait indefinitely.

How to restart SQL Server in single user mode?

From Startup Options :- Go to SQL Server Properties by right-clicking on the Server name in the Enterprise manager. Under the 'General' tab, click on 'Startup Parameters'. Enter a value of -m in the Parameter.

Does SQL Server 2000 clustering support load balancing?

SQL Server 2000 clustering does not provide load balancing; it provides failover support. To achieve load balancing, you need software that balances the load between clusters, not between servers within a cluster.

What is DTC?

The Microsoft Distributed Transaction Coordinator (MS DTC) is a transaction manager that allows client applications to include several different sources of data in one transaction. MS DTC coordinates committing the distributed transaction across all the servers enlisted in the transaction.

What is DTS?

Microsoft® SQL Server™ 2000 Data Transformation Services (DTS) is a set of graphical tools and programmable objects that lets you extract, transform, and consolidate data from disparate sources into single or multiple destinations.

What are defaults? Is there a column to which a default can't be bound?

A default is a value that will be used by a column, if no value is supplied to that column while inserting data. IDENTITY columns and timestamp columns can't have defaults bound to them.

Page 121: C Questions

What are the constraints ?

Table Constraints define rules regarding the values allowed in columns and are the standard mechanism for enforcing integrity. SQL Server 2000 supports five classes of constraints. NOT NULL , CHECK, UNIQUE, PRIMARY KEY, FOREIGN KEY.

What is Transaction?

A transaction is a sequence of operations performed as a single logical unit of work. A logical unit of work must exhibit four properties, called the ACID (Atomicity, Consistency, Isolation, and Durability) properties, to qualify as a transaction.

What is Isolation Level?

An isolation level determines the degree of isolation of data between concurrent transactions. The default SQL Server isolation level is Read Committed. A lower isolation level increases concurrency, but at the expense of data correctness. Conversely, a higher isolation level ensures that data is correct, but can affect concurrency negatively. The isolation level required by an application determines the locking behavior SQL Server uses. SQL-92 defines the following isolation levels, all of which are supported by SQL Server:

Read uncommitted (the lowest level where transactions are isolated only enough to ensure that physically corrupt data is not read).

Read committed (SQL Server default level). Repeatable read. Serializable (the highest level, where transactions are completely isolated from one another).

SQL Interview Questions and Frequently Asked Questions

1. The most important DDL statements in SQL are:

CREATE TABLE - creates a new database tableALTER TABLE - alters (changes) a database tableDROP TABLE - deletes a database table CREATE INDEX - creates an index (search key)DROP INDEX - deletes an index

Page 122: C Questions

2. Operators used in SELECT statements.

= Equal <> or != Not equal > Greater than < Less than >= Greater than or equal <= Less than or equal BETWEEN Between an inclusive range LIKE Search for a pattern

3. SELECT statements:

SELECT column_name(s) FROM table_name SELECT DISTINCT column_name(s) FROM table_name SELECT column FROM table WHERE column operator value SELECT column FROM table WHERE column LIKE pattern SELECT column,SUM(column) FROM table GROUP BY column SELECT column,SUM(column) FROM table GROUP BY column HAVING SUM(column) condition valueNote that single quotes around text values and numeric values should not be enclosed in quotes. Double quotes may be acceptable in some databases.

4. The SELECT INTO Statement is most often used to create backup copies of tables or for archiving records.

SELECT column_name(s) INTO newtable [IN externaldatabase] FROM source SELECT column_name(s) INTO newtable [IN externaldatabase] FROM source WHERE column_name operator value

5. The INSERT INTO Statements:

INSERT INTO table_name VALUES (value1, value2,....) INSERT INTO table_name (column1, column2,...) VALUES (value1, value2,....)

6. The Update Statement:

UPDATE table_name SET column_name = new_value WHERE column_name = some_value

7. The Delete Statements:

Page 123: C Questions

DELETE FROM table_name WHERE column_name = some_value Delete All Rows: DELETE FROM table_name or DELETE * FROM table_name

8. Sort the Rows:

SELECT column1, column2, ... FROM table_name ORDER BY columnX, columnY, ..SELECT column1, column2, ... FROM table_name ORDER BY columnX DESC SELECT column1, column2, ... FROM table_name ORDER BY columnX DESC, columnY ASC

9. The IN operator may be used if you know the exact value you want to return for at least one of the columns.

SELECT column_name FROM table_name WHERE column_name IN (value1,value2,..)

10. BETWEEN ... AND

SELECT column_name FROM table_name WHERE column_name BETWEEN value1 AND value2 The values can be numbers, text, or dates.

11. What is the use of CASCADE CONSTRAINTS?

When this clause is used with the DROP command, a parent table can be dropped even when a child table exists.

12. Why does the following command give a compilation error?

DROP TABLE &TABLE NAME; Variable names should start with an alphabet. Here the table name starts with an '&' symbol.

13. Which system tables contain information on privileges granted and privileges obtained?

USER_TAB_PRIVS_MADE, USER_TAB_PRIVS_RECD

14. Which system table contains information on constraints on all the tables created?obtained?

USER_CONSTRAINTS.

Page 124: C Questions

15. What is the difference between TRUNCATE and DELETE commands?

16. State true or false. !=, <>, ^= all denote the same operation?

True.

17. State true or false. EXISTS, SOME, ANY are operators in SQL?

True.

18. What will be the output of the following query?

SELECT REPLACE(TRANSLATE(LTRIM(RTRIM('!! ATHEN !!','!'), '!'), 'AN', '**'),'*','TROUBLE') FROM DUAL;?

19. What does the following query do?

SELECT SAL + NVL(COMM,0) FROM EMP;?This displays the total salary of all employees. The null values in the commission column will be replaced by 0 and added to salary.

20. What is the advantage of specifying WITH GRANT OPTION in the GRANT command?

The privilege receiver can further grant the privileges he/she has obtained from the owner to any other user.

21. Which command executes the contents of a specified file?

START or @.

22. What is the value of comm and sal after executing the following query if the initial value of ‘sal’ is 10000UPDATE EMP SET SAL = SAL + 1000, COMM = SAL*0.1;?

sal = 11000, comm = 1000.

23. Which command displays the SQL command in the SQL buffer, and then executes it?

RUN.

Page 125: C Questions

24. What command is used to get back the privileges offered by the GRANT command?

REVOKE.

25. What will be the output of the following query? SELECT DECODE(TRANSLATE('A','1234567890','1111111111'), '1','YES', 'NO' );? NO.

Explanation : The query checks whether a given string is a numerical digit.

26. Which date function is used to find the difference between two dates?

MONTHS_BETWEEN.

27. What operator performs pattern matching?

LIKE operator.

28. What is the use of the DROP option in the ALTER TABLE command?

It is used to drop constraints specified on the table.

29. What operator tests column for the absence of data?

IS NULL operator.

30. What are the privileges that can be granted on a table by a user to others?

Insert, update, delete, select, references, index, execute, alter, all.

31. Which function is used to find the largest integer less than or equal to a specific value?

FLOOR.

32. Which is the subset of SQL commands used to manipulate Oracle Database structures, including tables?

Data Definition Language (DDL).

33. What is the use of DESC in SQL?

Page 126: C Questions

DESC has two purposes. It is used to describe a schema as well as to retrieve rows from table in descending order.Explanation :The query SELECT * FROM EMP ORDER BY ENAME DESC will display the output sorted on ENAME in descending order.

34. What command is used to create a table by copying the structure of another table?

CREATE TABLE .. AS SELECT commandExplanation:To copy only the structure, the WHERE clause of the SELECT command should contain a FALSE statement as in the following.CREATE TABLE NEWTABLE AS SELECT * FROM EXISTINGTABLE WHERE 1=2;If the WHERE condition is true, then all the rows or rows satisfying the condition will be copied to the new table.

35. TRUNCATE TABLE EMP;DELETE FROM EMP;Will the outputs of the above two commands differ?

Both will result in deleting all the rows in the table EMP..

36. What is the output of the following query SELECT TRUNC(1234.5678,-2) FROM DUAL;?

1200.

37. What are the wildcards used for pattern matching.?

_ for single character substitution and % for multi-character substitution.

38. What is the parameter substitution symbol used with INSERT INTO command?

&

39. What's an SQL injection?

SQL Injection is when form data contains an SQL escape sequence and injects a new SQL query to be run.

40. What is difference between TRUNCATE & DELETE

Page 127: C Questions

TRUNCATE commits after deleting entire table i.e., cannot be rolled back. Database triggers do not fire on TRUNCATE DELETE allows the filtered deletion. Deleted records can be rolled back or committed. Database triggers fire on DELETE.

41. What is a join? Explain the different types of joins?

Join is a query, which retrieves related columns or rows from multiple tables. Self Join - Joining the table with itself.Equi Join - Joining two tables by equating two common columns.Non-Equi Join - Joining two tables by equating two common columns.Outer Join - Joining two tables in such a way that query can also retrieve rows that do not have corresponding join value in the other table.

42. What is the sub-query?

Sub-query is a query whose return values are used in filtering conditions of the main query.

43. What is correlated sub-query?

Correlated sub-query is a sub-query, which has reference to the main query.

44. Explain CONNECT BY PRIOR?

Retrieves rows in hierarchical order eg. select empno, ename from emp where.

45. Difference between SUBSTR and INSTR?

INSTR (String1, String2 (n, (m)), INSTR returns the position of the m-th occurrence of the string 2 in string1. The search begins from nth position of string1. SUBSTR (String1 n, m) SUBSTR returns a character string of size m in string1, starting from n-th position of string1.

46. Explain UNION, MINUS, UNION ALL and INTERSECT?

INTERSECT - returns all distinct rows selected by both queries. MINUS - returns all distinct rows selected by the first query but not by the second. UNION - returns all distinct rows selected by either query

Page 128: C Questions

UNION ALL - returns all rows selected by either query, including all duplicates.

47. What is ROWID?

ROWID is a pseudo column attached to each row of a table. It is 18 characters long, blockno, rownumber are the components of ROWID.

48. What is the fastest way of accessing a row in a table?

Using ROWID. CONSTRAINTS

49. What is an integrity constraint?

Integrity constraint is a rule that restricts values to a column in a table.

50. What is referential integrity constraint?

Maintaining data integrity through a set of rules that restrict the values of one or more columns of the tables based on the values of primary key or unique key of the referenced table.

51. What is the usage of SAVEPOINTS?

SAVEPOINTS are used to subdivide a transaction into smaller parts. It enables rolling back part of a transaction. Maximum of five save points are allowed.

52. What is ON DELETE CASCADE?

When ON DELETE CASCADE is specified Oracle maintains referential integrity by automatically removing dependent foreign key values if a referenced primary or unique key value is removed.

53. What are the data types allowed in a table?

CHAR, VARCHAR2, NUMBER, DATE, RAW, LONG and LONG RAW.

54. What is difference between CHAR and VARCHAR2? What is the maximum SIZE allowed for each type?

CHAR pads blank spaces to the maximum length. VARCHAR2 does not pad blank spaces. For CHAR the maximum length is 255 and 2000 for VARCHAR2.

Page 129: C Questions

55. How many LONG columns are allowed in a table? Is it possible to use LONG columns in WHERE clause or ORDER BY?

Only one LONG column is allowed. It is not possible to use LONG column in WHERE or ORDER BY clause.

56. What are the pre-requisites to modify datatype of a column and to add a column with NOT NULL constraint?

- To modify the datatype of a column the column must be empty.- To add a column with NOT NULL constrain, the table must be empty.

57. Where the integrity constraints are stored in data dictionary?

The integrity constraints are stored in USER_CONSTRAINTS.

58. How will you activate/deactivate integrity constraints?

The integrity constraints can be enabled or disabled by ALTER TABLE ENABLE CONSTRAINT / DISABLE CONSTRAINT.

59. If unique key constraint on DATE column is created, will it validate the rows that are inserted with SYSDATE?

It won't, Because SYSDATE format contains time attached with it.

60. What is a database link?

Database link is a named path through which a remote database can be accessed.

60. How to access the current value and next value from a sequence? Is it possible to access the current value in a session before accessing next value?

Sequence name CURRVAL, sequence name NEXTVAL. It is not possible. Only if you access next value in the session, current value can be accessed.

60.What is CYCLE/NO CYCLE in a Sequence?

CYCLE specifies that the sequence continue to generate values after reaching either maximum or minimum value. After pan-ascending sequence reaches its maximum value, it generates its minimum value. After a descending sequence reaches its minimum, it generates its

Page 130: C Questions

maximum. NO CYCLE specifies that the sequence cannot generate more values after reaching its maximum or minimum value.

61. What are the advantages of VIEW?

- To protect some of the columns of a table from other users. - To hide complexity of a query. - To hide complexity of calculations.

62. Can a view be updated/inserted/deleted? If Yes - under what conditions?

A View can be updated/deleted/inserted if it has only one base table if the view is based on columns from one or more tables then insert, update and delete is not possible.

63. If a view on a single base table is manipulated will the changes be reflected on the base table?

If changes are made to the tables and these tables are the base tables of a view, then the changes will be reference on the view.

64. Which of the following statements is true about implicit cursors?

1. Implicit cursors are used for SQL statements that are not named. 2. Developers should use implicit cursors with great care. 3. Implicit cursors are used in cursor for loops to handle data processing.4. Implicit cursors are no longer a feature in Oracle.

65. Which of the following is not a feature of a cursor FOR loop?

1. Record type declaration. 2. Opening and parsing of SQL statements. 3. Fetches records from cursor. 4. Requires exit condition to be defined.

66. A developer would like to use referential datatype declaration on a variable. The variable name is EMPLOYEE_LASTNAME, and the corresponding table and column is EMPLOYEE, and LNAME, respectively. How would the developer define this variable using referential datatypes?

Page 131: C Questions

1. Use employee.lname%type. 2. Use employee.lname%rowtype. 3. Look up datatype for EMPLOYEE column on LASTNAME table and use that. 4. Declare it to be type LONG.

67. Which three of the following are implicit cursor attributes?

1. %found 2. %too_many_rows 3. %notfound 4. %rowcount 5. %rowtype

68. If left out, which of the following would cause an infinite loop to occur in a simple loop?

1. LOOP 2. END LOOP 3. IF-THEN 4. EXIT

69. Which line in the following statement will produce an error?

1. cursor action_cursor is 2. select name, rate, action 3. into action_record 4. from action_table; 5. There are no errors in this statement.

70. The command used to open a CURSOR FOR loop is

1. open 2. fetch 3. parse 4. None, cursor for loops handle cursor opening implicitly.

71. What happens when rows are found using a FETCH statement

1. It causes the cursor to close 2. It causes the cursor to open 3. It loads the current row values into variables 4. It creates the variables to hold the current row values

Page 132: C Questions

72. Read the following code:

10. CREATE OR REPLACE PROCEDURE find_cpt11. (v_movie_id {Argument Mode} NUMBER, v_cost_per_ticket {argument mode} NUMBER)12. IS13. BEGIN14. IF v_cost_per_ticket > 8.5 THEN15. SELECT cost_per_ticket16. INTO v_cost_per_ticket17. FROM gross_receipt18. WHERE movie_id = v_movie_id;19. END IF;20. END;

Which mode should be used for V_COST_PER_TICKET? 1. IN 2. OUT 3. RETURN 4. IN OUT

73. Read the following code:22. CREATE OR REPLACE TRIGGER update_show_gross23. {trigger information}24. BEGIN25. {additional code}26. END;

The trigger code should only execute when the column, COST_PER_TICKET, is greater than $3. Which trigger information will you add?

1. WHEN (new.cost_per_ticket > 3.75)2. WHEN (:new.cost_per_ticket > 3.75 3. WHERE (new.cost_per_ticket > 3.75) 4. WHERE (:new.cost_per_ticket > 3.75)

74. What is the maximum number of handlers processed before the PL/SQL block is exited when an exception occurs?

1. Only one 2. All that apply 3. All referenced 4. None

Page 133: C Questions

77. For which trigger timing can you reference the NEW and OLD qualifiers?

1. Statement and Row 2. Statement only 3. Row only 4. Oracle Forms trigger

78. Read the following code:CREATE OR REPLACE FUNCTION get_budget(v_studio_id IN NUMBER)RETURN number ISv_yearly_budget NUMBER;BEGINSELECT yearly_budgetINTO v_yearly_budgetFROM studioWHERE id = v_studio_id;RETURN v_yearly_budget;END;Which set of statements will successfully invoke this function within SQL*Plus?

1. VARIABLE g_yearly_budget NUMBEREXECUTE g_yearly_budget := GET_BUDGET(11); 2. VARIABLE g_yearly_budget NUMBEREXECUTE :g_yearly_budget := GET_BUDGET(11); 3. VARIABLE :g_yearly_budget NUMBEREXECUTE :g_yearly_budget := GET_BUDGET(11); 4. VARIABLE g_yearly_budget NUMBER

31. CREATE OR REPLACE PROCEDURE update_theater32. (v_name IN VARCHAR v_theater_id IN NUMBER) IS33. BEGIN34. UPDATE theater35. SET name = v_name36. WHERE id = v_theater_id;37. END update_theater;

79. When invoking this procedure, you encounter the error:ORA-000:Unique constraint(SCOTT.THEATER_NAME_UK) violated.How should you modify the function to handle this error?

1. An user defined exception must be declared and associated with the error code and handled in the EXCEPTION section.2. Handle the error in EXCEPTION section by referencing the errorcode directly.

Page 134: C Questions

3. Handle the error in the EXCEPTION section by referencing the UNIQUE_ERROR predefined exception.4. Check for success by checking the value of SQL%FOUND immediately after the UPDATE statement.

80. Read the following code:

40. CREATE OR REPLACE PROCEDURE calculate_budget IS41. v_budget studio.yearly_budget%TYPE;42. BEGIN43. v_budget := get_budget(11);44. IF v_budget < 3000045. THEN46. set_budget(11,30000000);47. END IF;48. END;You are about to add an argument to CALCULATE_BUDGET. What effect will this have?

1. The GET_BUDGET function will be marked invalid and must be recompiled before the next execution.2. The SET_BUDGET function will be marked invalid and must be recompiled before the next execution. 3. Only the CALCULATE_BUDGET procedure needs to be recompiled. 4. All three procedures are marked invalid and must be recompiled.

81. Which procedure can be used to create a customized error message?

1. RAISE_ERROR 2. SQLERRM 3. RAISE_APPLICATION_ERROR4. RAISE_SERVER_ERROR

82. The CHECK_THEATER trigger of the THEATER table has been disabled. Which command can you issue to enable this trigger?

1. ALTER TRIGGER check_theater ENABLE; 2. ENABLE TRIGGER check_theater; 3. ALTER TABLE check_theater ENABLE check_theater; 4. ENABLE check_theater;

Page 135: C Questions

83. Examine this database trigger

52. CREATE OR REPLACE TRIGGER prevent_gross_modification53. {additional trigger information}54. BEGIN55. IF TO_CHAR(sysdate, DY) = MON56. THEN57. RAISE_APPLICATION_ERROR(-20000,Gross receipts cannot be deleted onMonday);58. END IF;59. END;This trigger must fire before each DELETE of the GROSS_RECEIPT table. It should fire only once for the entire DELETE statement. What additional information must you add?

1. BEFORE DELETE ON gross_receipt 2. AFTER DELETE ON gross_receipt 3. BEFORE (gross_receipt DELETE) 4. FOR EACH ROW DELETED FROM gross_receipt

84. Examine this function:

61. CREATE OR REPLACE FUNCTION set_budget62. (v_studio_id IN NUMBER, v_new_budget IN NUMBER) IS63. BEGIN64. UPDATE studio65. SET yearly_budget = v_new_budgetWHERE id = v_studio_id;IF SQL%FOUND THENRETURN TRUEl;ELSERETURN FALSE;END IF;COMMIT;END;Which code must be added to successfully compile this function?

1. Add RETURN right before the IS keyword. 2. Add RETURN number right before the IS keyword. 3. Add RETURN boolean right after the IS keyword. 4. Add RETURN boolean right before the IS keyword.

Page 136: C Questions

85. Under which circumstance must you recompile the package body after recompiling the package specification?

1. Altering the argument list of one of the package constructs 2. Any change made to one of the package constructs 3. Any SQL statement change made to one of the package constructs 4. Removing a local variable from the DECLARE section of one of the package constructs

86. Procedure and Functions are explicitly executed. This is different from a database trigger. When is a database trigger executed?

1. When the transaction is committed 2. During the data manipulation statement3. When an Oracle supplied package references the trigger 4. During a data manipulation statement and when the transaction is committed

87. Which Oracle supplied package can you use to output values and messages from database triggers, stored procedures and functions within SQL*Plus?

1. DBMS_DISPLAY 2. DBMS_OUTPUT 3. DBMS_LIST 4. DBMS_DESCRIBE

88. What occurs if a procedure or function terminates with failure without being handled?

1. Any DML statements issued by the construct are still pending and can be committed or rolled back. 2. Any DML statements issued by the construct are committed 3. Unless a GOTO statement is used to continue processing within the BEGIN section,the construct terminates. 4. The construct rolls back any DML statements issued and returns the unhandled exception to the calling environment.

89. Examine this code

71. BEGIN72. theater_pck.v_total_seats_sold_overall := theater_pck.get_total_for_year;73. END;For this code to be successful, what must be true?

Page 137: C Questions

1. Both the V_TOTAL_SEATS_SOLD_OVERALL variable and the GET_TOTAL_FOR_YEAR function must exist only in the body of the THEATER_PCK package. 2. Only the GET_TOTAL_FOR_YEAR variable must exist in the specification of the THEATER_PCK package. 3. Only the V_TOTAL_SEATS_SOLD_OVERALL variable must exist in thespecification of the THEATER_PCK package. 4. Both the V_TOTAL_SEATS_SOLD_OVERALL variable and the GET_TOTAL_FOR_YEAR function must exist in the specification of the THEATER_PCK package.

90. A stored function must return a value based on conditions that are determined at runtime. Therefore, the SELECT statement cannot be hard-coded and must be created dynamically when the function is executed. Which Oracle supplied package will enable this feature?

1. DBMS_DDL 2. DBMS_DML 3. DBMS_SYN 4. DBMS_SQL

91 How to implement ISNUMERIC function in SQL *Plus ?

Method 1:

Select length (translate(trim (column_name),'+-.0123456789',''))from dual;

Will give you a zero if it is a number or greater than zero if not numeric

(actually gives the count of non numeric characters)

Method 2:

select instr(translate('wwww','abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ','XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXX'),'X') FROM dual;

It returns 0 if it is a number, 1 if it is not.

92 How to Select last N records from a Table?

Page 138: C Questions

select * from (select rownum a, CLASS_CODE,CLASS_DESC from clm) where a > ( select (max(rownum)-10) from clm) Here N = 10The following query has a Problem of performance in the execution of the following query where the table ter.ter_master have 22231 records. So the results are obtained after hours.

Cursor rem_master(brepno VARCHAR2) ISselect a.* from ter.ter_master awhere NOT a.repno in (select repno from ermast) and(brepno = 'ALL' or a.repno > brepno)Order by a.repno

What are steps required tuning this query to improve its performance?

-Have an index on TER_MASTER.REPNO and one on ERMAST.REPNO-Be sure to get familiar with EXPLAIN PLAN. This can help you determine the execution path that Oracle takes. If you are using Cost Based Optimizer mode, then be sure that your statistics on TER_MASTER are up-to-date. -Also, you can change your SQL to:

SELECT a.*FROM ter.ter_master aWHERE NOT EXISTS (SELECT b.repno FROM ermast bWHERE a.repno=b.repno) AND(a.brepno = 'ALL' or a.repno > a.brepno)ORDER BY a.repno;

93. What is the difference between Truncate and Delete interms of Referential Integrity?

DELETE removes one or more records in a table, checking referential Constraints (to see if there are dependent child records) and firing any DELETE triggers. In the order you are deleting (child first then parent) There will be no problems.

TRUNCATE removes ALL records in a table. It does not execute any triggers. Also, it only checks for the existence (and status) of another foreign key Pointing to the table. If one exists and is enabled, then you will get The following error. This

Page 139: C Questions

is true even if you do the child tables first. ORA-02266: unique/primary keys in table referenced by enabled foreign keys You should disable the foreign key constraints in the child tables before issuing the TRUNCATE command, then re-enable them afterwards.

Top     

PL-SQL Interview Questions and Frequently Asked Questions

1. Describe the difference between a procedure, function and anonymous pl/sql block.

Level: LowExpected answer : Candidate should mention use of DECLARE statement, a function mustreturn a value while a procedure doesn?t have to.

2. What is a mutating table error and how can you get around it?

Level: IntermediateExpected answer: This happens with triggers. It occurs because the trigger is trying to update a row it is currently using. The usual fix involves either use of views or temporary tables so the database is selecting from one while updating the other.

3. Describe the use of %ROWTYPE and %TYPE in PL/SQL

Level: LowExpected answer: %ROWTYPE allows you to associate a variable with an entire table row.The %TYPE associates a variable with a single column type.

4. What packages (if any) has Oracle provided for use by developers?

Level: Intermediate to highExpected answer: Oracle provides the DBMS_ series of packages. There are many which developers should be aware of such as DBMS_SQL, DBMS_PIPE,

Page 140: C Questions

DBMS_TRANSACTION,DBMS_LOCK, DBMS_ALERT, DBMS_OUTPUT, DBMS_JOB, DBMS_UTILITY, DBMS_DDL, UTL_FILE. If they can mention a few of these and describe how they used them, even better. If they include the SQL routines provided by Oracle, great, but not really what was asked.

5. Describe the use of PL/SQL tables

Level: IntermediateExpected answer: PL/SQL tables are scalar arrays that can be referenced by a binary integer. They can be used to hold values for use in later queries or calculations. In Oracle 8 they will be able to be of the %ROWTYPE designation, or RECORD.

6. When is a declare statement needed ?

Level: LowThe DECLARE statement is used in PL/SQL anonymous blocks such as with stand alone, non-stored PL/SQL procedures. It must come first in a PL/SQL stand alone file if it is used.

7. In what order should a open/fetch/loop set of commands in a PL/SQL block be implemented if you use the NOTFOUND cursor variable in the exit when statement? Why?

Level: IntermediateExpected answer: OPEN then FETCH then LOOP followed by the exit when. If not specified in this order will result in the final return being done twice because of the way the %NOTFOUND is handled by PL/SQL.

8. What are SQLCODE and SQLERRM and why are they important for PL/SQL developers?

Level: IntermediateExpected answer: SQLCODE returns the value of the error number for the last error encountered. The SQLERRM returns the actual error message for the last error encountered. They can be used in exception handling to report, or, store in an error log table, the error that occurred in the code. These are especially useful for the WHEN OTHERS exception.

Page 141: C Questions

9. How can you find within a PL/SQL block, if a cursor is open?

Level: LowExpected answer: Use the %ISOPEN cursor status variable.

10. How can you generate debugging output from PL/SQL?

Level:Intermediate to highExpected answer: Use the DBMS_OUTPUT package. Another possible method is to just use the SHOW ERROR command, but this only shows errors. The DBMS_OUTPUT package can be used to show intermediate results from loops and the status of variables as the procedure is executed. The new package UTL_FILE canalso be used.

11. What are the types of triggers?

Level:Intermediate to highExpected Answer: There are 12 types of triggers in PL/SQL that consist of combinations of the BEFORE, AFTER, ROW, TABLE, INSERT, UPDATE, DELETE and ALL key words:BEFORE ALL ROW INSERTAFTER ALL ROW INSERTBEFORE INSERTAFTER INSERT etc.

Top     

SQL / SQLPlus Interview Questions and Frequently Asked Questions

1. How can variables be passed to a SQL routine?

Level: LowExpected answer: By use of the & symbol. For passing in variables the numbers 1-8 can be used (&1, &2,...,&8) to pass the values after the command into the SQLPLUS session. To be prompted for a specific variable, place the ampersanded variable in the code itself:"select * from dba_tables where owner=&owner_name;" . Use of double

Page 142: C Questions

ampersands tells SQLPLUS to resubstitute the value for each subsequent use of the variable, a single ampersand will cause a reprompt for the value unless an ACCEPT statement is used to get the value from the user.

2. You want to include a carriage return/linefeed in your output from a SQL script, how can you do this?

Level: Intermediate to highExpected answer: The best method is to use the CHR() function (CHR(10) is a return/linefeed) and the concatenation function "||". Another method, although it is hard to document and isn?t always portable is to use the return/linefeed as a part of a quoted string.

3. How can you call a PL/SQL procedure from SQL?

Level: IntermediateExpected answer: By use of the EXECUTE (short form EXEC) command.

4. How do you execute a host operating system command from within SQL?

Level: LowExpected answer: By use of the exclamation point "!" (in UNIX and some other OS) or the HOST (HO) command.

5. You want to use SQL to build SQL, what is this called and give an example

Level: Intermediate to highExpected answer: This is called dynamic SQL. An example would be:set lines 90 pages 0 termout off feedback off verify offspool drop_all.sqlselect ?drop user ?||username||? cascade;? from dba_userswhere username not in ("SYS?,?SYSTEM?);spool offEssentially you are looking to see that they know to include a command (in this case DROP USER...CASCADE;) and that you need to concatenate using the ?||? the values selected from the database.

6. What SQLPlus command is used to format output from a select?

Level: lowExpected answer: This is best done with the COLUMN command.

Page 143: C Questions

7. You want to group the following set of select returns, what can you group on?

Max(sum_of_cost), min(sum_of_cost), count(item_no), item_noLevel: IntermediateExpected answer: The only column that can be grouped on is the "item_no" column, the rest have aggregate functions associated with them.

8. What special Oracle feature allows you to specify how the cost based system treats a SQL statement?

Level: Intermediate to high Expected answer: The COST based system allows the use of HINTs to control the optimizer path selection. If they can give some example hints such as FIRST ROWS, ALL ROWS, USING INDEX, STAR, even better.

9. You want to determine the location of identical rows in a table before attempting to place a unique index on the table, how can this be done?

Level: High Expected answer: Oracle tables always have one guaranteed unique column, the rowid column. If you use a min/max function against your rowid and then select against the proposed primary key you can squeeze out the rowids of the duplicate rows pretty quick. For example: select rowid from emp e where e.rowid > (select min(x.rowid) from emp x where x.emp_no = e.emp_no); In the situation where multiple columns make up the proposed key, they must all be used in the where clause.

10. What is a Cartesian product?

Level: LowExpected answer: A Cartesian product is the result of an unrestricted join of two or more tables. The result set of a three table Cartesian product will have x * y * z number of rows where x, y, z correspond to the number of rows in each table involved in the join.

11. You are joining a local and a remote table, the network manager complains about the traffic involved, how can you reduce the network traffic?

Level: High Expected answer: Push the processing of the remote data to the remote instance by using a view to pre-select the information for the join. This will result in only the data required for the join being sent across.

Page 144: C Questions

12. What is the default ordering of an ORDER BY clause in a SELECT statement?

Level: Low Expected answer: Ascending

13. What is tkprof and how is it used?

Level: Intermediate to high Expected answer: The tkprof tool is a tuning tool used to determine cpu and execution times for SQL statements. You use it by first setting timed_statistics to true in the initialization file and then turning on tracing for either the entire database via the sql_trace parameter or for the session using the ALTER SESSION command. Once the trace file is generated you run the tkprof tool against the trace file and then look at the output from the tkprof tool. This can also be used to generate explain plan output.

14. What is explain plan and how is it used?

Level: Intermediate to high Expected answer: The EXPLAIN PLAN command is a tool to tune SQL statements. To use it you must have an explain_table generated in the user you are running the explain plan for. This is created using the utlxplan.sql script. Once the explain plan table exists you run the explain plan command giving as its argument the SQL statement to be explained. The explain_plan table is then queried to see the execution plan of the statement. Explain plans can also be run using tkprof.

15. How do you set the number of lines on a page of output? The width?

Level: Low Expected answer: The SET command in SQLPLUS is used to control the number of lines generated per page and the width of those lines, for example SET PAGESIZE 60 LINESIZE 80 will generate reports that are 60 lines long with a line width of 80 characters. The PAGESIZE and LINESIZE options can be shortened to PAGES and LINES.

16. How do you prevent output from coming to the screen?

Level: LowExpected answer: The SET option TERMOUT controls output to the screen. Setting TERMOUT OFF turns off screen output. This option can be shortened to TERM.

17. How do you prevent Oracle from giving you informational messages during and after a SQL statement execution?

Page 145: C Questions

Level: Low Expected answer: The SET options FEEDBACK and VERIFY can be set to OFF.

18. How do you generate file output from SQL?

Level: Low Expected answer: By use of the SPOOL command

SQL Interview Questions | Frequently Asked Questions (FAQs)

     SQL Basic Questions

     SQL Questions

     Client Server Questions

     PL/SQL Questions

     SQL / SQL Plus Questions

SQL Basics

SQLSQL is an English like language consisting of commands to store, retrieve, maintain & regulate access to your database.

SQL*PlusSQL*Plus is an application that recognizes & executes SQL commands & specialized SQL*Plus commands that can customize reports, provide help & edit facility & maintain system variables.

Page 146: C Questions

NVLNVL : Null value function converts a null value to a non-null value for the purpose of evaluating an expression. Numeric Functions accept numeric I/P & return numeric values. They are MOD, SQRT, ROUND, TRUNC & POWER.

Date FunctionsDate Functions are ADD_MONTHS, LAST_DAY, NEXT_DAY, MONTHS_BETWEEN & SYSDATE.

Character FunctionsCharacter Functions are INITCAP, UPPER, LOWER, SUBSTR & LENGTH. Additional functions are GREATEST & LEAST. Group Functions returns results based upon groups of rows rather than one result per row, use group functions. They are AVG, COUNT, MAX, MIN & SUM.

TTITLE & BTITLETTITLE & BTITLE are commands to control report headings & footers.

COLUMNCOLUMN command define column headings & format data values.

BREAKBREAK command clarify reports by suppressing repeated values, skipping lines & allowing for controlled break points.

COMPUTEcommand control computations on subsets created by the BREAK command.

SETSET command changes the system variables affecting the report environment.

SPOOLSPOOL command creates a print file of the report.

JOIN JOIN is the form of SELECT command that combines info from two or more tables.Types of Joins are Simple (Equijoin & Non-Equijoin), Outer & Self join.Equijoin returns rows from two or more tables joined together based upon a equality condition in the WHERE clause.Non-Equijoin returns rows from two or more tables based upon a relationship other than the equality condition in the WHERE clause.Outer Join combines two or more tables returning those rows from one

Page 147: C Questions

table that have no direct match in the other table.Self Join joins a table to itself as though it were two separate tables.

Union Union is the product of two or more tables.

IntersectIntersect is the product of two tables listing only the matching rows.

MinusMinus is the product of two tables listing only the non-matching rows.

Correlated SubqueryCorrelated Subquery is a subquery that is evaluated once for each row processed by the parent statement. Parent statement can be Select, Update or Delete. Use CRSQ to answer multipart questions whose answer depends on the value in each row processed by parent statement.

Multiple columnsMultiple columns can be returned from a Nested Subquery.

Sequences Sequences are used for generating sequence numbers without any overhead of locking. Drawback is that after generating a sequence number if the transaction is rolled back, then that sequence number is lost.

Synonyms Synonyms is the alias name for table, views, sequences & procedures and are created for reasons of Security and Convenience.Two levels are Public - created by DBA & accessible to all the users. Private - Accessible to creator only. Advantages are referencing without specifying the owner and Flexibility to customize a more meaningful naming convention.

Indexes Indexes are optional structures associated with tables used to speed query execution and/or guarantee uniqueness. Create an index if there are frequent retrieval of fewer than 10-15% of the rows in a large table and columns are referenced frequently in the WHERE clause. Implied tradeoff is query speed vs. update speed. Oracle automatically update indexes. Concatenated index max. is 16 columns.

Data types Max. columns in a table is 255. Max. Char size is 255, Long is 64K &

Page 148: C Questions

Number is 38 digits.Cannot Query on a long column.Char, Varchar2 Max. size is 2000 & default is 1 byte.Number(p,s) p is precision range 1 to 38, s is scale -84 to 127.Long Character data of variable length upto 2GB.Date Range from Jan 4712 BC to Dec 4712 AD.Raw Stores Binary data (Graphics Image & Digitized Sound). Max. is 255 bytes.Mslabel Binary format of an OS label. Used primarily with Trusted Oracle.

Order of SQL statement execution Where clause, Group By clause, Having clause, Order By clause & Select.

Transaction Transaction is defined as all changes made to the database between successive commits.

Commit Commit is an event that attempts to make data in the database identical to the data in the form. It involves writing or posting data to the database and committing data to the database. Forms check the validity of the data in fields and records during a commit. Validity check are uniqueness, consistency and db restrictions.

Posting Posting is an event that writes Inserts, Updates & Deletes in the forms to the database but not committing these transactions to the database.

Rollback Rollback causes work in the current transaction to be undone.

Savepoint Savepoint is a point within a particular transaction to which you may rollback without rolling back the entire transaction.

Set Transaction Set Transaction is to establish properties for the current transaction.

Locking Locking are mechanisms intended to prevent destructive interaction between users accessing data. Locks are used to achieve.

Page 149: C Questions

Consistency Consistency : Assures users that the data they are changing or viewing is not changed until the are thro' with it.

Integrity Assures database data and structures reflects all changes made to them in the correct sequence. Locks ensure data integrity and maximum concurrent access to data. Commit statement releases all locks. Types of locks are given below.Data Locks protects data i.e. Table or Row lock.Dictionary Locks protects the structure of database object i.e. ensures table's structure does not change for the duration of the transaction.Internal Locks & Latches protects the internal database structures. They are automatic.Exclusive Lock allows queries on locked table but no other activity is allowed.Share Lock allows concurrent queries but prohibits updates to the locked tables.Row Share allows concurrent access to the locked table but prohibits for a exclusive table lock.Row Exclusive same as Row Share but prohibits locking in shared mode.Shared Row Exclusive locks the whole table and allows users to look at rows in the table but prohibit others from locking the table in share or updating them.Share Update are synonymous with Row Share.

DeadlockDeadlock is a unique situation in a multi user system that causes two or more users to wait indefinitely for a locked resource. First user needs a resource locked by the second user and the second user needs a resource locked by the first user. To avoid dead locks, avoid using exclusive table lock and if using, use it in the same sequence and use Commit frequently to release locks.

Mutating TableMutating Table is a table that is currently being modified by an Insert, Update or Delete statement. Constraining Table is a table that a triggering statement might need to read either directly for a SQL statement or indirectly for a declarative Referential Integrity constraints. Pseudo Columns behaves like a column in a table but are not actually stored in the table. E.g. Currval, Nextval, Rowid, Rownum, Level etc.

SQL*LoaderSQL*Loader is a product for moving data in external files into tables in

Page 150: C Questions

an Oracle database. To load data from external files into an Oracle database, two types of input must be provided to SQL*Loader : the data itself and the control file. The control file describes the data to be loaded. It describes the Names and format of the data files, Specifications for loading data and the Data to be loaded (optional). Invoking the loader sqlload username/password controlfilename <options>.

Top     

SQL Questions

1. The most important DDL statements in SQL are:

CREATE TABLE - creates a new database table ALTER TABLE - alters (changes) a database table DROP TABLE - deletes a database table CREATE INDEX - creates an index (search key) DROP INDEX - deletes an index

2. Operators used in SELECT statements.

= Equal <> or != Not equal > Greater than < Less than >= Greater than or equal <= Less than or equal BETWEEN Between an inclusive range LIKE Search for a pattern

3. SELECT statements:

SELECT column_name(s) FROM table_name SELECT DISTINCT column_name(s) FROM table_name SELECT column FROM table WHERE column operator value SELECT column FROM table WHERE column LIKE pattern SELECT column,SUM(column) FROM table GROUP BY column SELECT column,SUM(column) FROM table GROUP BY column HAVING SUM(column) condition valueNote that single quotes around text values and numeric values should not be enclosed in quotes. Double quotes may be acceptable in some databases.

4. The SELECT INTO Statement is most often used to create backup copies of tables or for archiving records.

Page 151: C Questions

SELECT column_name(s) INTO newtable [IN externaldatabase] FROM source SELECT column_name(s) INTO newtable [IN externaldatabase] FROM source WHERE column_name operator value

5. The INSERT INTO Statements:

INSERT INTO table_name VALUES (value1, value2,....) INSERT INTO table_name (column1, column2,...) VALUES (value1, value2,....)

6. The Update Statement:

UPDATE table_name SET column_name = new_value WHERE column_name = some_value

7. The Delete Statements:

DELETE FROM table_name WHERE column_name = some_value Delete All Rows: DELETE FROM table_name or DELETE * FROM table_name

8. Sort the Rows:

SELECT column1, column2, ... FROM table_name ORDER BY columnX, columnY, ..SELECT column1, column2, ... FROM table_name ORDER BY columnX DESC SELECT column1, column2, ... FROM table_name ORDER BY columnX DESC, columnY ASC

9. The IN operator may be used if you know the exact value you want to return for at least one of the columns.

SELECT column_name FROM table_name WHERE column_name IN (value1,value2,..)

10. BETWEEN ... AND

SELECT column_name FROM table_name WHERE column_name BETWEEN value1 AND value2 The values can be numbers, text, or dates.

11. What is the use of CASCADE CONSTRAINTS?

Page 152: C Questions

When this clause is used with the DROP command, a parent table can be dropped even when a child table exists.

12. Why does the following command give a compilation error?

DROP TABLE &TABLE_NAME; Variable names should start with an alphabet. Here the table name starts with an '&' symbol.

Top     

13. Which system tables contain information on privileges granted and privileges obtained?

USER_TAB_PRIVS_MADE, USER_TAB_PRIVS_RECD

14. Which system table contains information on constraints on all the tables created?obtained?

USER_CONSTRAINTS.

15. What is the difference between TRUNCATE and DELETE commands?

16. State true or false. !=, <>, ^= all denote the same operation?

True.

17. State true or false. EXISTS, SOME, ANY are operators in SQL?

True.

18. What will be the output of the following query?

SELECT REPLACE(TRANSLATE(LTRIM(RTRIM('!! ATHEN !!','!'), '!'), 'AN', '**'),'*','TROUBLE') FROM DUAL;?TROUBLETHETROUBLE. p>

19. What does the following query do?

SELECT SAL + NVL(COMM,0) FROM EMP;?This displays the total salary of all employees. The null values in the commission column will be replaced by 0 and added to salary.

Page 153: C Questions

20. What is the advantage of specifying WITH GRANT OPTION in the GRANT command?

The privilege receiver can further grant the privileges he/she has obtained from the owner to any other user.

21. Which command executes the contents of a specified file?

START or @.

22. What is the value of comm and sal after executing the following query if the initial value of ‘sal’ is 10000UPDATE EMP SET SAL = SAL + 1000, COMM = SAL*0.1;?

sal = 11000, comm = 1000.

23. Which command displays the SQL command in the SQL buffer, and then executes it?

RUN.

24. What command is used to get back the privileges offered by the GRANT command?

REVOKE.

Top     

25. What will be the output of the following query? SELECT DECODE(TRANSLATE('A','1234567890','1111111111'), '1','YES', 'NO' );?

NO.

Explanation : The query checks whether a given string is a numerical digit.

26. Which date function is used to find the difference between two dates?

MONTHS_BETWEEN.

27. What operator performs pattern matching?

LIKE operator.

Page 154: C Questions

28. What is the use of the DROP option in the ALTER TABLE command?

It is used to drop constraints specified on the table.

29. What operator tests column for the absence of data?

IS NULL operator.

30. What are the privileges that can be granted on a table by a user to others?

Insert, update, delete, select, references, index, execute, alter, all.

31. Which function is used to find the largest integer less than or equal to a specific value?

FLOOR.

32. Which is the subset of SQL commands used to manipulate Oracle Database structures, including tables?

Data Definition Language (DDL).

33. What is the use of DESC in SQL?

DESC has two purposes. It is used to describe a schema as well as to retrieve rows from table in descending order.Explanation :The query SELECT * FROM EMP ORDER BY ENAME DESC will display the output sorted on ENAME in descending order.

34. What command is used to create a table by copying the structure of another table?

CREATE TABLE .. AS SELECT commandExplanation:To copy only the structure, the WHERE clause of the SELECT command should contain a FALSE statement as in the following.CREATE TABLE NEWTABLE AS SELECT * FROM EXISTINGTABLE WHERE 1=2;If the WHERE condition is true, then all the rows or rows satisfying the condition will be copied to the new table.

Page 155: C Questions

35. TRUNCATE TABLE EMP;DELETE FROM EMP;Will the outputs of the above two commands differ?

Both will result in deleting all the rows in the table EMP.

Top     

36. What is the output of the following query SELECT TRUNC(1234.5678,-2) FROM DUAL;?

1200.

37. What are the wildcards used for pattern matching.?

_ for single character substitution and % for multi-character substitution.

38. What is the parameter substitution symbol used with INSERT INTO command?

&

39. What's an SQL injection?

SQL Injection is when form data contains an SQL escape sequence and injects a new SQL query to be run.

40. What is difference between TRUNCATE & DELETE

TRUNCATE commits after deleting entire table i.e., cannot be rolled back. Database triggers do not fire on TRUNCATE DELETE allows the filtered deletion. Deleted records can be rolled back or committed. Database triggers fire on DELETE.

41. What is a join? Explain the different types of joins?

Join is a query, which retrieves related columns or rows from multiple tables. Self Join - Joining the table with itself.Equi Join - Joining two tables by equating two common columns.Non-Equi Join - Joining two tables by equating two common columns.Outer Join - Joining two tables in such a way that query can also retrieve rows that do not have corresponding join value in the other table.

Page 156: C Questions

42. What is the sub-query?

Sub-query is a query whose return values are used in filtering conditions of the main query.

43. What is correlated sub-query?

Correlated sub-query is a sub-query, which has reference to the main query.

44. Explain CONNECT BY PRIOR?

Retrieves rows in hierarchical order eg. select empno, ename from emp where.

45. Difference between SUBSTR and INSTR?

INSTR (String1, String2 (n, (m)), INSTR returns the position of the m-th occurrence of the string 2 in string1. The search begins from nth position of string1. SUBSTR (String1 n, m) SUBSTR returns a character string of size m in string1, starting from n-th position of string1.

46. Explain UNION, MINUS, UNION ALL and INTERSECT?

INTERSECT - returns all distinct rows selected by both queries. MINUS - returns all distinct rows selected by the first query but not by the second. UNION - returns all distinct rows selected by either query UNION ALL - returns all rows selected by either query, including all duplicates.

47. What is ROWID?

ROWID is a pseudo column attached to each row of a table. It is 18 characters long, blockno, rownumber are the components of ROWID.

48. What is the fastest way of accessing a row in a table?

Using ROWID. CONSTRAINTS

Top     

49. What is an integrity constraint?

Page 157: C Questions

Integrity constraint is a rule that restricts values to a column in a table.

50. What is referential integrity constraint?

Maintaining data integrity through a set of rules that restrict the values of one or more columns of the tables based on the values of primary key or unique key of the referenced table.

51. What is the usage of SAVEPOINTS?

SAVEPOINTS are used to subdivide a transaction into smaller parts. It enables rolling back part of a transaction. Maximum of five save points are allowed.

52. What is ON DELETE CASCADE?

When ON DELETE CASCADE is specified Oracle maintains referential integrity by automatically removing dependent foreign key values if a referenced primary or unique key value is removed.

53. What are the data types allowed in a table?

CHAR, VARCHAR2, NUMBER, DATE, RAW, LONG and LONG RAW.

54. What is difference between CHAR and VARCHAR2? What is the maximum SIZE allowed for each type?

CHAR pads blank spaces to the maximum length. VARCHAR2 does not pad blank spaces. For CHAR the maximum length is 255 and 2000 for VARCHAR2.

55. How many LONG columns are allowed in a table? Is it possible to use LONG columns in WHERE clause or ORDER BY?

Only one LONG column is allowed. It is not possible to use LONG column in WHERE or ORDER BY clause.

56. What are the pre-requisites to modify datatype of a column and to add a column with NOT NULL constraint?

- To modify the datatype of a column the column must be empty.- To add a column with NOT NULL constrain, the table must be empty.

57. Where the integrity constraints are stored in data dictionary?

Page 158: C Questions

The integrity constraints are stored in USER_CONSTRAINTS.

58. How will you activate/deactivate integrity constraints?

The integrity constraints can be enabled or disabled by ALTER TABLE ENABLE CONSTRAINT / DISABLE CONSTRAINT.

59. If unique key constraint on DATE column is created, will it validate the rows that are inserted with SYSDATE?

It won't, Because SYSDATE format contains time attached with it.

60. What is a database link?

Database link is a named path through which a remote database can be accessed.

60. How to access the current value and next value from a sequence? Is it possible to access the current value in a session before accessing next value?

Sequence name CURRVAL, sequence name NEXTVAL. It is not possible. Only if you access next value in the session, current value can be accessed.

60.What is CYCLE/NO CYCLE in a Sequence?

CYCLE specifies that the sequence continue to generate values after reaching either maximum or minimum value. After pan-ascending sequence reaches its maximum value, it generates its minimum value. After a descending sequence reaches its minimum, it generates its maximum. NO CYCLE specifies that the sequence cannot generate more values after reaching its maximum or minimum value.

61. What are the advantages of VIEW?

- To protect some of the columns of a table from other users. - To hide complexity of a query. - To hide complexity of calculations.

62. Can a view be updated/inserted/deleted? If Yes - under what conditions?

Page 159: C Questions

A View can be updated/deleted/inserted if it has only one base table if the view is based on columns from one or more tables then insert, update and delete is not possible.

63. If a view on a single base table is manipulated will the changes be reflected on the base table?

If changes are made to the tables and these tables are the base tables of a view, then the changes will be reference on the view.

Top     

64. Which of the following statements is true about implicit cursors?

1. Implicit cursors are used for SQL statements that are not named. 2. Developers should use implicit cursors with great care. 3. Implicit cursors are used in cursor for loops to handle data processing.4. Implicit cursors are no longer a feature in Oracle.

65. Which of the following is not a feature of a cursor FOR loop?

1. Record type declaration. 2. Opening and parsing of SQL statements. 3. Fetches records from cursor. 4. Requires exit condition to be defined.

66. A developer would like to use referential datatype declaration on a variable. The variable name is EMPLOYEE_LASTNAME, and the corresponding table and column is EMPLOYEE, and LNAME, respectively. How would the developer define this variable using referential datatypes?

1. Use employee.lname%type. 2. Use employee.lname%rowtype. 3. Look up datatype for EMPLOYEE column on LASTNAME table and use that. 4. Declare it to be type LONG.

67. Which three of the following are implicit cursor attributes?

1. %found 2. %too_many_rows 3. %notfound

Page 160: C Questions

4. %rowcount 5. %rowtype

68. If left out, which of the following would cause an infinite loop to occur in a simple loop?

1. LOOP 2. END LOOP 3. IF-THEN 4. EXIT

69. Which line in the following statement will produce an error?

1. cursor action_cursor is 2. select name, rate, action 3. into action_record 4. from action_table; 5. There are no errors in this statement.

70. The command used to open a CURSOR FOR loop is

1. open 2. fetch 3. parse 4. None, cursor for loops handle cursor opening implicitly.

71. What happens when rows are found using a FETCH statement

1. It causes the cursor to close 2. It causes the cursor to open 3. It loads the current row values into variables 4. It creates the variables to hold the current row values

72. Read the following code:00 CREATE OR REPLACE PROCEDURE find_cpt01. (v_movie_id {Argument Mode} NUMBER, v_cost_per_ticket {argument mode} NUMBER)02. IS03. BEGIN04. IF v_cost_per_ticket > 8.5 THEN05. SELECT cost_per_ticket06. INTO v_cost_per_ticket07. FROM gross_receipt08. WHERE movie_id = v_movie_id;

Page 161: C Questions

09. END IF;10. END;Which mode should be used for V_COST_PER_TICKET? 1. IN 2. OUT 3. RETURN 4. IN OUT

Top     

73. Read the following code:1. CREATE OR REPLACE TRIGGER update_show_gross2. {trigger information}3. BEGIN4. {additional code}5. END;

The trigger code should only execute when the column, COST_PER_TICKET, is greater than $3. Which trigger information will you add?

1. WHEN (new.cost_per_ticket > 3.75)2. WHEN (:new.cost_per_ticket > 3.75 3. WHERE (new.cost_per_ticket > 3.75) 4. WHERE (:new.cost_per_ticket > 3.75)

74. What is the maximum number of handlers processed before the PL/SQL block is exited when an exception occurs?

1. Only one 2. All that apply 3. All referenced 4. None

77. For which trigger timing can you reference the NEW and OLD qualifiers?

1. Statement and Row 2. Statement only 3. Row only 4. Oracle Forms trigger

78. Read the following code:CREATE OR REPLACE FUNCTION get_budget(v_studio_id IN NUMBER)RETURN number IS

Page 162: C Questions

v_yearly_budget NUMBER;

BEGINSELECT yearly_budgetINTO v_yearly_budgetFROM studioWHERE id = v_studio_id;

RETURN v_yearly_budget;END;Which set of statements will successfully invoke this function within SQL*Plus? '

1. VARIABLE g_yearly_budget NUMBEREXECUTE g_yearly_budget := GET_BUDGET(11); 2. VARIABLE g_yearly_budget NUMBEREXECUTE :g_yearly_budget := GET_BUDGET(11); 3. VARIABLE :g_yearly_budget NUMBEREXECUTE :g_yearly_budget := GET_BUDGET(11); 4. VARIABLE g_yearly_budget NUMBER

31. CREATE OR REPLACE PROCEDURE update_theater32. (v_name IN VARCHAR v_theater_id IN NUMBER) IS33. BEGIN34. UPDATE theater35. SET name = v_name36. WHERE id = v_theater_id;37. END update_theater;

79. When invoking this procedure, you encounter the error: ORA-000: Unique constraint(SCOTT.THEATER_NAME_UK) violated.How should you modify the function to handle this error?

1. An user defined exception must be declared and associated with the error code and handled in the EXCEPTION section.2. Handle the error in EXCEPTION section by referencing the error code directly. 3. Handle the error in the EXCEPTION section by referencing the UNIQUE_ERROR predefined exception.4. Check for success by checking the value of SQL%FOUND immediately after the UPDATE statement.

80. Read the following code: 40. CREATE OR REPLACE PROCEDURE calculate_budget IS

Page 163: C Questions

41. v_budget studio.yearly_budget%TYPE;42. BEGIN43. v_budget := get_budget(11);44. IF v_budget < 3000045. THEN46. set_budget(11,30000000);47. END IF;48. END;

You are about to add an argument to CALCULATE_BUDGET. What effect will this have?

1. The GET_BUDGET function will be marked invalid and must be recompiled before the next execution.2. The SET_BUDGET function will be marked invalid and must be recompiled before the next execution. 3. Only the CALCULATE_BUDGET procedure needs to be recompiled. 4. All three procedures are marked invalid and must be recompiled.

81. Which procedure can be used to create a customized error message? 1. RAISE_ERROR 2. SQLERRM 3. RAISE_APPLICATION_ERROR 4. RAISE_SERVER_ERROR

82. The CHECK_THEATER trigger of the THEATER table has been disabled. Which command can you issue to enable this trigger? 1. ALTER TRIGGER check_theater ENABLE; 2. ENABLE TRIGGER check_theater; 3. ALTER TABLE check_theater ENABLE check_theater; 4. ENABLE check_theater;

83. Examine this database trigger 52. CREATE OR REPLACE TRIGGER prevent_gross_modification53. {additional trigger information}54. BEGIN55. IF TO_CHAR(sysdate, DY) = MON56. THEN57. RAISE_APPLICATION_ERROR(-20000,Gross receipts cannot be deleted on Monday);58. END IF;59. END;

Page 164: C Questions

This trigger must fire before each DELETE of the GROSS_RECEIPT table. It should fire only once for the entire DELETE statement. What additional information must you add?

1. BEFORE DELETE ON gross_receipt 2. AFTER DELETE ON gross_receipt 3. BEFORE (gross_receipt DELETE) 4. FOR EACH ROW DELETED FROM gross_receipt

Top     

84. Examine this function: 61. CREATE OR REPLACE FUNCTION set_budget62. (v_studio_id IN NUMBER, v_new_budget IN NUMBER) IS63. BEGIN64. UPDATE studio65. SET yearly_budget = v_new_budgetWHERE id = v_studio_id;

IF SQL%FOUND THENRETURN TRUEl;ELSERETURN FALSE;END IF;

COMMIT;END;

Which code must be added to successfully compile this function?

1. Add RETURN right before the IS keyword. 2. Add RETURN number right before the IS keyword. 3. Add RETURN boolean right after the IS keyword. 4. Add RETURN boolean right before the IS keyword.

85. Under which circumstance must you recompile the package body after recompiling the package specification?

1. Altering the argument list of one of the package constructs 2. Any change made to one of the package constructs 3. Any SQL statement change made to one of the package constructs 4. Removing a local variable from the DECLARE section of one of the package constructs

Page 165: C Questions

86. Procedure and Functions are explicitly executed. This is different from a database trigger. When is a database trigger executed?

1. When the transaction is committed 2. During the data manipulation statement 3. When an Oracle supplied package references the trigger 4. During a data manipulation statement and when the transaction is committed

87. Which Oracle supplied package can you use to output values and messages from database triggers, stored procedures and functions within SQL*Plus?

1. DBMS_DISPLAY 2. DBMS_OUTPUT 3. DBMS_LIST 4. DBMS_DESCRIBE

88. What occurs if a procedure or function terminates with failure without being handled?

1. Any DML statements issued by the construct are still pending and can be committed or rolled back. 2. Any DML statements issued by the construct are committed 3. Unless a GOTO statement is used to continue processing within the BEGIN section, the construct terminates. 4. The construct rolls back any DML statements issued and returns the unhandled exception to the calling environment.

89. Examine this code 71. BEGIN72. theater_pck.v_total_seats_sold_overall := theater_pck.get_total_for_year;73. END;

For this code to be successful, what must be true?

1. Both the V_TOTAL_SEATS_SOLD_OVERALL variable and the GET_TOTAL_FOR_YEAR function must exist only in the body of the THEATER_PCK package. 2. Only the GET_TOTAL_FOR_YEAR variable must exist in the specification of the THEATER_PCK package. 3. Only the V_TOTAL_SEATS_SOLD_OVERALL variable must exist in the specification of the THEATER_PCK package. 4. Both the V_TOTAL_SEATS_SOLD_OVERALL variable and the GET_TOTAL_FOR_YEAR function must exist in the specification of the THEATER_PCK package.

Page 166: C Questions

90 A stored function must return a value based on conditions that are determined at runtime. Therefore, the SELECT statement cannot be hard-coded and must be created dynamically when the function is executed. Which Oracle supplied package will enable this feature?

1. DBMS_DDL 2. DBMS_DML 3. DBMS_SYN 4. DBMS_SQL

90 A stored function must return a value based on conditions that are determined at runtime. Therefore, the SELECT statement cannot be hard-coded and must be created dynamically when the function is executed. Which Oracle supplied package will enable this feature?

1. DBMS_DDL 2. DBMS_DML 3. DBMS_SYN 4. DBMS_SQL

91 How to implement ISNUMERIC function in SQL *Plus ?

Method 1:

Select length (translate (trim (column_name),' +-.0123456789',' ')) from dual ;

Will give you a zero if it is a number or greater than zero if not numeric (actually gives the count of non numeric characters)

Method 2:

select instr(translate('wwww','abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ','XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'),'X')FROM dual;

It returns 0 if it is a number, 1 if it is not.

Top     

92 How to Select last N records from a Table?

Page 167: C Questions

select * from (select rownum a, CLASS_CODE,CLASS_DESC from clm)where a > ( select (max(rownum)-10) from clm)

Here N = 10

The following query has a Problem of performance in the execution of the following query where the table ter.ter_master have 22231 records. So the results are obtained after hours.

Cursor rem_master(brepno VARCHAR2) ISselect a.* from ter.ter_master awhere NOT a.repno in (select repno from ermast) and(brepno = 'ALL' or a.repno > brepno)Order by a.repno

What are steps required tuning this query to improve its performance?

-Have an index on TER_MASTER.REPNO and one on ERMAST.REPNO

-Be sure to get familiar with EXPLAIN PLAN. This can help you determine the execution path that Oracle takes. If you are using Cost Based Optimizer mode, then be sure that your statistics on TER_MASTER are up-to-date. -Also, you can change your SQL to:

SELECT a.*FROM ter.ter_master aWHERE NOT EXISTS (SELECT b.repno FROM ermast bWHERE a.repno=b.repno) AND(a.brepno = 'ALL' or a.repno > a.brepno)ORDER BY a.repno;

93 What is the difference between Truncate and Delete interms of Referential Integrity?

DELETE removes one or more records in a table, checking referential Constraints (to see if there are dependent child records) and firing any DELETE triggers. In the order you are deleting (child first then parent) There will be no problems. TRUNCATE removes ALL records in a table. It does not execute any triggers. Also, it only checks for the existence (and status) of another foreign key Pointing to the table. If one exists and is enabled, then you will get The following error. This is true even if you do the child tables first. ORA-02266: unique/primary keys in table referenced by enabled foreign keys

Page 168: C Questions

You should disable the foreign key constraints in the child tables before issuing the TRUNCATE command, then re-enable them afterwards.

CLIENT/SERVER

94. What does preemptive in preemptive multitasking mean ?

Preemptive refers to the fact that each task is alloted fixed time slots and at the end of that time slot the next task is started.

95. What does the OLTP stands for ?

OLTP stands for On Line Transaction Processing

96. What is the most important requirement for OLTP ?

OLTP requires real time response.

97. In a client server environment, what would be the major work that the client deals with ?

The client deals with the user interface part of the system.

98. Why is the most of the processing done at the sever ?

To reduce the network traffic and for application sharing and implementing business rules.

99. What does teh term upsizing refer to ?

Applications that have outgrown their environment are re-engineered to run in a larger environment. This is upsizing.

100. What does one do when one is rightsizing ?

With rightsizing, one would move applications to the most appropriate server platforms.

101. What does the term downsizing refer to ?

A host based application is re-engineered to run in smaller or LAN based environment.

102. What is event trigger ?

Page 169: C Questions

An event trigger, a segment of code which is associated with each event and is fired when the event occurs.

103. Why do stored procedures reduce network traffic ?

When a stored procedure is called, only the procedure call is sent to the server and not the statements that the procedure contains.

Top     

104. What are the types of processes that a server runs ?

Foreground process and Background process.

105. What is a event handler ?

An event handler is a routine that is written to respond to a particular event.

106. What is an integrity constraint ?

An integrity constraint allows the definition of certain restrictions, at the table level, on the data that is entered into a table.

107. What are the various uses of database triggers ?

Database triggers can be used to enforce business rules, to maintain derived values and perform value-based auditing.

108. What is a transaction ?

A transaction is a set of operations that begin when the first DML is issued and end when a commit or rollback is issued. BEGIN COMMIT/ROLLBACK are the boundries of a transaction.

109. Why are the integrity constraints preferred to database triggers ?

Because it is easier to define an integrity constraint than a database trigger.

110. Why is it better to use an integrity constraint to validate data in a table than to use a stored procedure ?

Because an integrity constraint is automatically checked while data is inserted into a table. A stored has to be specifically invoked.

Page 170: C Questions

111. What are the three components of a client server model ?

A Client,A Server and A Network/Communication software.

112. What are the advantages of client/server model ?

Flexibility of the system, scalability, cost saving, centralised control and implementation of business rules, increase of developers productivity, portability, improved network and resource utilization.

113. What are the disadvantages of the client/server model ?

Heterogeneity of the system results in reduced reliablity. May not be suitable for all applications. Managing and tuning networks becomes difficult.

114. What are the different topologies available for network ?

Star,Bus,Ring.

115. What is the first work of Client process ?

A client process at first establishes connection with the Server.

115. What are the responsibilities of a Server ?

1. Manage resources optimally across multiple clients.2. Controlling database access and security.3. Protecting the databse and recovering it from crashes.4. Enforcing integrity rules globally.

116. In a Client/Server context, what does API (Application Programming Interface) refer to ?

An API, in a Client/Server context, is a specification of a set of functions for communication between the client and the server.

117. Give some examples of standard API??s ?

Open Database Connectivity (ODBC),Integrated Database Application Programming Interface (IDAPI),

Page 171: C Questions

XOpenSQL/CLI

118. What is the main advantage of developing an application using an API ?

The application can be connected to any back end server that is supported by the API.

119. What is the main disadvantage of developing an application using an API ?

The application cannot use any special features of the backend server.

120. Why is an event driven program referred to a passive program ?

Because an event driven program is always waiting for something to happen before processing.

120. What are the four types of events ?

1. System Events.2. Control Events3. User Events4. Other Events.

121. What is the difference between file server and a database server ?

A file server just transfers all the data requested by all its client and the client processes the data while a database server runs the query and sends only the query output.

122. What is inheritance ?

Inheritance is a method by which properties and methods of an existing object are automatically passed to any object derived from it.

123. What are the two components of ODBC ?

1. An ODBC manager/administrator and2. ODBC driver.

Top     

Page 172: C Questions

124. What is the function of a ODBC manager ?

The ODBC Manager manages all the data sources that exists in the system.

125. What is the function of a ODBC Driver ?

The ODBC Driver allows the developer to talk to the back end database.

126. What description of a data source is required for ODBC ?

The name of the DBMS, the location of the source and the database dependent information.

127. How is a connection establised by ODBC ?

ODBC uses the description of the datasource available in the ODBC.INI file to load the required drivers to access that particular back end database.

PL/SQL Questions:

1. Describe the difference between a procedure, function and anonymous pl/sql block.

Level: LowExpected answer : Candidate should mention use of DECLARE statement, a function must return a value while a procedure doesn?t have to.

2. What is a mutating table error and how can you get around it?

Level: IntermediateExpected answer: This happens with triggers. It occurs because the trigger is trying to update a row it is currently using. The usual fix involves either use of views or temporary tables so the database is selecting from one while updating the other.

3. Describe the use of %ROWTYPE and %TYPE in PL/SQL

Level: LowExpected answer: %ROWTYPE allows you to associate a variable with an entire table row. The %TYPE associates a variable with a single column type.

Page 173: C Questions

4. What packages (if any) has Oracle provided for use by developers?

Level: Intermediate to highExpected answer: Oracle provides the DBMS_ series of packages. There are many which developers should be aware of such as DBMS_SQL, DBMS_PIPE, DBMS_TRANSACTION, DBMS_LOCK, DBMS_ALERT, DBMS_OUTPUT, DBMS_JOB, DBMS_UTILITY, DBMS_DDL, UTL_FILE. If they can mention a few of these and describe how they used them, even better. If they include the SQL routines provided by Oracle, great, but not really what was asked.

5. Describe the use of PL/SQL tables

Level: IntermediateExpected answer: PL/SQL tables are scalar arrays that can be referenced by a binary integer. They can be used to hold values for use in later queries or calculations. In Oracle 8 they will be able to be of the %ROWTYPE designation, or RECORD.

6. When is a declare statement needed ?

Level: LowThe DECLARE statement is used in PL/SQL anonymous blocks such as with stand alone, non-stored PL/SQL procedures. It must come first in a PL/SQL stand alone file if it is used.

7. In what order should a open/fetch/loop set of commands in a PL/SQL block be implemented if you use the %NOTFOUND cursor variable in the exit when statement? Why?

Level: IntermediateExpected answer: OPEN then FETCH then LOOP followed by the exit when. If not specified in this order will result in the final return being done twice because of the way the %NOTFOUND is handled by PL/SQL.

8. What are SQLCODE and SQLERRM and why are they important for PL/SQL developers?

Level: IntermediateExpected answer: SQLCODE returns the value of the error number for the last error encountered. The SQLERRM returns the actual error message for the last error encountered. They can be used in exception handling to report, or, store in an error log table, the error that occurred in the code. These are especially useful for the WHEN OTHERS exception.

Page 174: C Questions

9. How can you find within a PL/SQL block, if a cursor is open?

Level: LowExpected answer: Use the %ISOPEN cursor status variable.

10. How can you generate debugging output from PL/SQL?

Level:Intermediate to highExpected answer: Use the DBMS_OUTPUT package. Another possible method is to just use the SHOW ERROR command, but this only shows errors. The DBMS_OUTPUT package can be used to show intermediate results from loops and the status of variables as the procedure is executed. The new package UTL_FILE can also be used.

11. What are the types of triggers?

Level:Intermediate to highExpected Answer: There are 12 types of triggers in PL/SQL that consist of combinations of the BEFORE, AFTER, ROW, TABLE, INSERT, UPDATE, DELETE and ALL key words:BEFORE ALL ROW INSERTAFTER ALL ROW INSERTBEFORE INSERTAFTER INSERT etc.

Top     

SQL/ SQLPlus Questions

1. How can variables be passed to a SQL routine?

Level: LowExpected answer: By use of the & symbol. For passing in variables the numbers 1-8 can be used (&1, &2,...,&8) to pass the values after the command into the SQLPLUS session. To be prompted for a specific variable, place the ampersanded variable in the code itself:"select * from dba_tables where owner=&owner_name;" . Use of double ampersands tells SQLPLUS to resubstitute the value for each subsequent use of the variable, a single ampersand will cause a reprompt for the value unless an ACCEPT statement is used to get the value from the user.

2. You want to include a carriage return/linefeed in your output from a SQL script, how can you do this?

Page 175: C Questions

Level: Intermediate to highExpected answer: The best method is to use the CHR() function (CHR(10) is a return/linefeed) and the concatenation function "||". Another method, although it is hard to document and isn?t always portable is to use the return/linefeed as a part of a quoted string.

3. How can you call a PL/SQL procedure from SQL?

Level: IntermediateExpected answer: By use of the EXECUTE (short form EXEC) command.

4. How do you execute a host operating system command from within SQL?

Level: LowExpected answer: By use of the exclamation point "!" (in UNIX and some other OS) or the HOST (HO) command.

5. You want to use SQL to build SQL, what is this called and give an example

Level: Intermediate to highExpected answer: This is called dynamic SQL. An example would be:set lines 90 pages 0 termout off feedback off verify offspool drop_all.sqlselect ?drop user ?||username||? cascade;? from dba_userswhere username not in ("SYS?,?SYSTEM?);spool offEssentially you are looking to see that they know to include a command (in this case DROP USER...CASCADE;) and that you need to concatenate using the ?||? the values selected from the database.

6. What SQLPlus command is used to format output from a select?

Level: lowExpected answer: This is best done with the COLUMN command.

7. You want to group the following set of select returns, what can you group on?

Max(sum_of_cost), min(sum_of_cost), count(item_no), item_noLevel: IntermediateExpected answer: The only column that can be grouped on is the "item_no" column, the rest have aggregate functions associated with them.

Page 176: C Questions

8. What special Oracle feature allows you to specify how the cost based system treats a SQL statement?

Level: Intermediate to highExpected answer: The COST based system allows the use of HINTs to control the optimizer path selection. If they can give some example hints such as FIRST ROWS, ALL ROWS, USING INDEX, STAR, even better.

9. You want to determine the location of identical rows in a table before attempting to place a unique index on the table, how can this be done?

Level: HighExpected answer: Oracle tables always have one guaranteed unique column, the rowid column. If you use a min/max function against your rowid and then select against the proposed primary key you can squeeze out the rowids of the duplicate rows pretty quick. For example:select rowid from emp ewhere e.rowid > (select min(x.rowid)from emp xwhere x.emp_no = e.emp_no);In the situation where multiple columns make up the proposed key, they must all be used in the where clause.

10. What is a Cartesian product?

Level: LowExpected answer: A Cartesian product is the result of an unrestricted join of two or more tables. The result set of a three table Cartesian product will have x * y * z number of rows where x, y, z correspond to the number of rows in each table involved in the join.

11. You are joining a local and a remote table, the network manager complains about the traffic involved, how can you reduce the network traffic?

Level: HighExpected answer: Push the processing of the remote data to the remote instance by using a view to pre-select the information for the join. This will result in only the data required for the join being sent across.

12. What is the default ordering of an ORDER BY clause in a SELECT statement?

Page 177: C Questions

Level: LowExpected answer: Ascending

13. What is tkprof and how is it used?

Level: Intermediate to highExpected answer: The tkprof tool is a tuning tool used to determine cpu and execution times for SQL statements. You use it by first setting timed_statistics to true in the initialization file and then turning on tracing for either the entire database via the sql_trace parameter or for the session using the ALTER SESSION command. Once the trace file is generated you run the tkprof tool against the trace file and then look at the output from the tkprof tool. This can also be used to generate explain plan output.

14. What is explain plan and how is it used?

Level: Intermediate to highExpected answer: The EXPLAIN PLAN command is a tool to tune SQL statements. To use it you must have an explain_table generated in the user you are running the explain plan for. This is created using the utlxplan.sql script. Once the explain plan table exists you run the explain plan command giving as its argument the SQL statement to be explained. The explain_plan table is then queried to see the execution plan of the statement. Explain plans can also be run using tkprof.

15. How do you set the number of lines on a page of output? The width?

Level: LowExpected answer: The SET command in SQLPLUS is used to control the number of lines generated per page and the width of those lines, for example SET PAGESIZE 60 LINESIZE 80 will generate reports that are 60 lines long with a line width of 80 characters. The PAGESIZE and LINESIZE options can be shortened to PAGES and LINES.

16. How do you prevent output from coming to the screen?

Level: LowExpected answer: The SET option TERMOUT controls output to the screen. Setting TERMOUT OFF turns off screen output. This option can be shortened to TERM.

17. How do you prevent Oracle from giving you informational messages during and after a SQL statement execution?

Page 178: C Questions

Level: LowExpected answer: The SET options FEEDBACK and VERIFY can be set to OFF.

18. How do you generate file output from SQL?

Level: LowExpected answer: By use of the SPOOL command

JAVA Interview Questions | Frequently Asked Questions (FAQs)

Next >>

1. What does a well-written OO program look like?

A well-written OO program exhibits recurring structures that promote abstraction, flexibility, modularity and elegance.

2. Can you have virtual functions in Java?

Yes, all functions in Java are virtual by default. This is actually a pseudo trick question because the word "virtual" is not part of the naming convention in Java (as it is in C++, C-sharp and VB.NET), so this would be a foreign concept for someone who has only coded in Java. Virtual functions or virtual methods are functions or methods that will be redefined in derived classes.

3. Jack developed a program by using a Map container to hold key/value pairs. He wanted to make a change to the map. He

Page 179: C Questions

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

If Jack made a clone of the map, any changes to the clone or the original map would be seen on both maps, because the clone of Map is a shallow copy. So Jack made a wrong decision.

4. What is more advisable to create a thread, by implementing a Runnable interface or by extending Thread class?

Strategically speaking, threads created by implementing Runnable interface are more advisable. If you create a thread by extending a thread class, you cannot extend any other class. If you create a thread by implementing Runnable interface, you save a space for your class to extend another class now or in future.

5. What is NullPointerException and how to handle it?

When an object is not initialized, the default value is null. When the following things happen, the NullPointerException is thrown: --Calling the instance method of a null object. --Accessing or modifying the field of a null object. --Taking the length of a null as if it were an array. --Accessing or modifying the slots of null as if it were an array. --Throwing null as if it were a Throwable value. The NullPointerException is a runtime exception. The best practice is to catch such exception even if it is not required by language design.

6. An application needs to load a library before it starts to run, how to code??

One option is to use a static block to load a library before anything is called. For example, class Test { static { System.loadLibrary("path-to-library-file"); } .... } When you call new Test(), the static block will be called first before any initialization happens. Note that the static block position may matter.

7. What is a platform?

A platform is the hardware or software environment in which a program runs. Most platforms can be described as a combination of the operating system and hardware, like Windows 2000 and XP, Linux, Solaris, and MacOS.

8. What is transient variable?

Page 180: C Questions

Transient variable can't be serialize. For example if a variable is declared as transient in a Serializable class and the class is written to an ObjectStream, the value of the variable can't be written to the stream instead when the class is retrieved from the ObjectStream the value of the variable becomes null.

9. Name the containers which uses Border Layout as their default layout?

Containers which uses Border Layout as their default are: window, Frame and Dialog classes.

10. What do you understand by Synchronization?

Synchronization is a process of controlling the access of shared resources by the multiple threads in such a manner that only one thread can access one resource at a time. In non synchronized multithreaded application, it is possible for one thread to modify a shared object while another thread is in the process of using or updating the object's value.Synchronization prevents such type of data corruption.E.g. Synchronizing a function:public synchronized void Method1 () {// Appropriate method-related code. }E.g. Synchronizing a block of code inside a function:public myFunction (){synchronized (this) { // Synchronized code here.}}

11. What is Collection API?

Answer: The Collection API is a set of classes and interfaces that support operation on collections of objects. These classes and interfaces are more flexible, more powerful, and more regular than the vectors, arrays, and hashtables if effectively replaces. Example of classes: HashSet, HashMap, ArrayList, LinkedList, TreeSet and TreeMap.Example of interfaces: Collection, Set, List and Map.

12. Is Iterator a Class or Interface? What is its use?

Answer: Iterator is an interface which is used to step through the elements of a Collection.

Page 181: C Questions

13. What is similarities/difference between an Abstract class and Interface?

Differences are as follows: Interfaces provide a form of multiple inheritance. A class can extend only one other class. Interfaces are limited to public methods and constants with no implementation. Abstract classes can have a partial implementation, protected parts, static methods, etc. A Class may implement several interfaces. But in case of abstract class, a class may extend only one abstract class. Interfaces are slow as it requires extra indirection to to find corresponding method in in the actual class. Abstract classes are fast. Similarities:

Neither Abstract classes or Interface can be instantiated.

14. How to define an Abstract class?

A class containing abstract method is called Abstract class. An Abstract class can't be instantiated.Example of Abstract class:abstract class testAbstractClass {protected String myString; public String getMyString() { return myString; } public abstract string anyAbstractFunction();}

15. How to define an Interface?

In Java Interface defines the methods but does not implement them. Interface can include constants. A class that implements the interfaces is bound to implement all the methods defined in Interface.Emaple of Interface:

public interface sampleInterface {public void functionOne();

public long CONSTANT_ONE = 1000; }

16. How to make a class or a bean serializable?

By implementing either the java.io.Serializable interface, or the java.io.Externalizable interface. As long as one class in a class's

Page 182: C Questions

inheritance hierarchy implements Serializable or Externalizable, that class is serializable.

17. How many methods in the Serializable interface?

There is no method in the Serializable interface. The Serializable interface acts as a marker, telling the object serialization tools that your class is serializable.

18. How many methods in the Externalizable interface?

There are two methods in the Externalizable interface. You have to implement these two methods in order to make your class externalizable. These two methods are readExternal() and writeExternal().

19. What is the difference between Serializalble and Externalizable interface?

When you use Serializable interface, your class is serialized automatically by default. But you can override writeObject() and readObject() two methods to control more complex object serailization process. When you use Externalizable interface, you have a complete control over your class's serialization process.

20. What is a transient variable?

A transient variable is a variable that may not be serialized. If you don't want some field to be serialized, you can mark that field transient or static.

21. Which containers use a border layout as their default layout?

The Window, Frame and Dialog classes use a border layout as their default layout.

22. How are Observer and Observable used?

Objects that subclass the Observable class maintain a list of observers. When an Observable object is updated, it invokes the update() method of each of its observers to notify the observers that it has changed state. The Observer interface is implemented by objects that observe Observable objects.

23. What is synchronization and why is it important?

Page 183: C Questions

With respect to multithreading, synchronization is the capability to control the access of multiple threads to shared resources. Without synchronization, it is possible for one thread to modify a shared object while another thread is in the process of using or updating that object's value. This often causes dirty data and leads to significant errors.

24. What are synchronized methods and synchronized statements?

Synchronized methods are methods that are used to control access to a method or an object. A thread only executes a synchronized method after it has acquired the lock for the method's object or class. Synchronized statements are similar to synchronized methods. A synchronized statement can only be executed after a thread has acquired the lock for the object or class referenced in the synchronized statement.

25. What are three ways in which a thread can enter the waiting state?

A thread can enter the waiting state by invoking its sleep() method, by blocking on IO, by unsuccessfully attempting to acquire an object's lock, or by invoking an object's wait() method. It can also enter the waiting state by invoking its (deprecated) suspend() method.

26. Can a lock be acquired on a class?

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

27. What's new with the stop(), suspend() and resume() methods in JDK 1.2?

The stop(), suspend() and resume() methods have been deprecated in JDK 1.2.

28. What is the preferred size of a component?

The preferred size of a component is the minimum component size that will allow the component to display normally.

29. What method is used to specify a container's layout?

The set Layout() method is used to specify a container's layout.

30. Which containers use a Flow Layout as their default layout?

Page 184: C Questions

The Panel and Applet classes use the Flow Layout as their default layout.

31. What is thread?

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

32. What is multi-threading?

Multi-threading means various threads that run in a system.

33. How does multi-threading take place on a computer with a single CPU?

The operating system's task scheduler allocates execution time to multiple tasks. By quickly switching between executing tasks, it creates the impression that tasks execute sequentially.

34. How to create a thread in a program?

You have two ways to do so. First, making your class "extends" Thread class. Second, making your class "implements" Runnable interface. Put jobs in a run() method and call start() method to start the thread.

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

Yes. You can lock an object by putting it in a "synchronized" block. The locked object is inaccessible to any thread other than the one that explicitly claimed it.

36. Can each Java object keep track of all the threads that want to exclusively access to it?

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

37. What state does a thread enter when it terminates its processing?

When a thread terminates its processing, it enters the dead state.

38. What invokes a thread's run() method?

After a thread is started, via its start() method of the Thread class, the JVM invokes the thread's run() method when the thread is initially executed.

Page 185: C Questions

39. What is the purpose of the wait(), notify(), and notifyAll() methods? The wait(),notify(), and notifyAll() methods are used to provide an efficient way for threads to communicate each other.

40. What are the high-level thread states?

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

41. What is the difference between yielding and sleeping?

When a task invokes its yield() method, it returns to the ready state. When a task invokes its sleep() method, it returns to the waiting state.

42. What happens when a thread cannot acquire a lock on an object?

If a thread attempts to execute a synchronized method or synchronized statement and is unable to acquire an object's lock, it enters the waiting state until the lock becomes available.

43. What is the difference between Process and Thread?

A process can contain multiple threads. In most multithreading operating systems, a process gets its own memory address space; a thread doesn't. Threads typically share the heap belonging to their parent process. For instance, a JVM runs in a single process in the host O/S. Threads in the JVM share the heap belonging to that process; that's why several threads may access the same object. Typically, even though they share a common heap, threads have their own stack space. This is how one thread's invocation of a method is kept separate from another's. This is all a gross oversimplification, but it's accurate enough at a high level. Lots of details differ between operating systems. Process vs. Thread A program vs. similar to a sequential program an run on its own vs. Cannot run on its own Unit of allocation vs. Unit of execution Have its own memory space vs. Share with others Each process has one or more threads vs. Each thread belongs to one process Expensive, need to context switch vs. Cheap, can use process memory and may not need to context switch More secure. One process cannot corrupt another process vs. Less secure. A thread can write the memory used by another thread

44. What is the Collections API?

The Collections API is a set of classes and interfaces that support operations on collections of objects.

Page 186: C Questions

45. What is the List interface?

The List interface provides support for ordered collections of objects.

46. What is the Vector class?

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

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

A (non-local) inner class may be declared as public, protected, private, static, final, or abstract.

48. If a method is declared as protected, where may the method be accessed?

A protected method may only be accessed by classes or interfaces of the same package or by subclasses of the class in which it is declared.

49. What is an Iterator interface?

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

50. How many bits are used to represent Unicode, ASCII, UTF-16, and UTF-8 characters?

Unicode requires 16 bits and ASCII require 7 bits. Although the ASCII character set uses only 7 bits, it is usually represented as 8 bits. UTF-8 represents characters using 8, 16, and 18 bit patterns. UTF-16 uses 16-bit and larger bit patterns.

51. Is sizeof a keyword?

The sizeof operator is not a keyword in Java.

52. What are wrapped classes?

Wrapped classes are classes that allow primitive types to be accessed as objects.

53. Does garbage collection guarantee that a program will not run out of memory?

Page 187: C Questions

No, it doesn't. It is possible for programs to use up memory resources faster than they are garbage collected. It is also possible for programs to create objects that are not subject to garbage collection.

54. What is the difference between preemptive scheduling and time slicing?

Under preemptive scheduling, the highest priority task executes until it enters the waiting or dead states or a higher priority task comes into existence. Under time slicing, a task executes for a predefined slice of time and then reenters the pool of ready tasks. The scheduler then determines which task should execute next, based on priority and other factors.

55. Name Component subclasses that support painting?

The Canvas, Frame, Panel, and Applet classes support painting.

56. What is a native method?

A native method is a method that is implemented in a language other than Java.

57. How can you write a loop indefinitely?

for(;;)--for loop; while(true)--always true, etc.

58. Can an anonymous class be declared as implementing an interface and extending a class?

An anonymous class may implement an interface or extend a superclass, but may not be declared to do both.

59. CWhat is the purpose of finalization?

The purpose of finalization is to give an unreachable object the opportunity to perform any cleanup processing before the object is garbage collected.

60. Which class is the superclass for every class.

Object.

61. How many methods in Object class?

Page 188: C Questions

This question is not asked to test your memory. It tests you how well you know Java. Ten in total.clone() equals() & hashcode() getClass() finalize() wait() & notify() toString()

62. How does Java handle integer overflows and underflows?

It uses low order bytes of the result that can fit into the size of the type allowed by the operation.

63. What is the numeric promotion?

Numeric promotion is used with both unary and binary bitwise operators. This means that byte, char, and short values are converted to int values before a bitwise operator is applied.If a binary bitwise operator has one long operand, the other operand is converted to a long value.The type of the result of a bitwise operation is the type to which the operands have been promoted. For example:short a = 5;byte b = 10;long c = 15;The type of the result of (a+b) is int, not short or byte. The type of the result of (a+c) or (b+c) is long.

64. Is the numeric promotion available in other plantform?

Yes. Because Java is implemented using a platform-independent virtual machine, bitwise operations always yield the same result, even when run on machines that use radically different CPUs.

65. What is the difference between the Boolean & operator and the && operator?

If an expression involving the Boolean & operator is evaluated, both operands are evaluated. Then the & operator is applied to the operand. When an expression involving the && operator is evaluated, the first operand is evaluated. If the first operand returns a value of true then the second operand is evaluated. The && operator is then applied to the first and second operands. If the first operand evaluates to false, the evaluation of the second operand is skipped.

Page 189: C Questions

Operator & has no chance to skip both sides evaluation and && operator does. If asked why, give details as above.

65. When is the ArithmeticException throwQuestion: What is the GregorianCalendar class?

The GregorianCalendar provides support for traditional Western calendars.

66. What is the SimpleTimeZone class?

The SimpleTimeZone class provides support for a Gregorian calendar.

67. Which Container method is used to cause a container to be laid out and redisplayed?

validate()

68. What is the Properties class?

The properties class is a subclass of Hashtable that can be read from or written to a stream. It also provides the capability to specify a set of default values to be used.

69. What is the purpose of the Runtime class?

The purpose of the Runtime class is to provide access to the Java runtime system.

70. What is the purpose of the System class?

The purpose of the System class is to provide access to system resources.

71. What is the purpose of the finally clause of a try-catch-finally statement?

The finally clause is used to provide the capability to execute code no matter whether or not an exception is thrown or caught.

72. What is the Locale class?

The Locale class is used to tailor program output to the conventions of a particular geographic, political, or cultural region.

73. What is an abstract method?

Page 190: C Questions

An abstract method is a method whose implementation is deferred to a subclass. Or, a method that has no implementation.

74. What is the difference between interface and abstract class?

interface contains methods that must be abstract; abstract class may contain concrete methods. interface contains variables that must be static and final; abstract class may contain non-final and final variables. members in an interface are public by default, abstract class may contain non-public members. interface is used to "implements"; whereas abstract class is used to "extends". interface can be used to achieve multiple inheritance; abstract class can be used as a single inheritance. interface can "extends" another interface, abstract class can "extends" another class and "implements" multiple interfaces. interface is absolutely abstract; abstract class can be invoked if a main() exists. interface is more flexible than abstract class because one class can only "extends" one super class, but "implements" multiple interfaces. If given a choice, use interface instead of abstract class.

75. What is a static method?

A static method is a method that belongs to the class rather than any object of the class and doesn't apply to an object or even require that any objects of the class have been instantiated.

76. What is a protected method?

A protected method is a method that can be accessed by any method in its package and inherited by any subclass of its class.

77. What is the difference between a static and a non-static inner class?

A non-static inner class may have object instances that are associated with instances of the class's outer class. A static inner class does not have any object instances.

78. What is an object's lock and which object's have locks?

An object's lock is a mechanism that is used by multiple threads to obtain synchronized access to the object. A thread may execute a synchronized method of an object only after it has acquired the object's lock. All objects and classes have locks. A class's lock is acquired on the class's Class object.

Page 191: C Questions

79. When can an object reference be cast to an interface reference?

An object reference can be cast to an interface reference when the object implements the referenced interface.

80. What is the difference between a Window and a Frame?

The Frame class extends Window to define a main application window that can have a menu bar.

81. What is the difference between a Window and a Frame?

Heavy weight components like Abstract Window Toolkit (AWT), depend on the local windowing toolkit. For example, java.awt.Button is a heavy weight component, when it is running on the Java platform for Unix platform, it maps to a real Motif button. In this relationship, the Motif button is called the peer to the java.awt.Button. If you create two Buttons, two peers and hence two Motif Buttons are also created. The Java platform communicates with the Motif Buttons using the Java Native Interface. For each and every component added to the application, there is an additional overhead tied to the local windowing system, which is why these components are called heavy weight.

82. Which package has light weight components?

javax.Swing package. All components in Swing, except JApplet, JDialog, JFrame and JWindow are lightweight components.

83. What are peerless components?

The peerless components are called light weight components.

84. What is the difference between the Font and FontMetrics classes?

The FontMetrics class is used to define implementation-specific properties, such as ascent and descent, of a Font object

85. What is the difference between the Reader/Writer class hierarchy and the InputStream/OutputStream class hierarchy?

The Reader/Writer class hierarchy is character-oriented, and the InputStream/OutputStream class hierarchy is byte-oriented.

Page 192: C Questions

86. 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.

87. What is the difference between throw and throws keywords?

The throw keyword denotes a statement that causes an exception to be initiated. It takes the Exception object to be thrown as argument. The exception will be caught by an immediately encompassing try-catch construction or propagated further up the calling hierarchy. The throws keyword is a modifier of a method that designates that exceptions may come out of the mehtod, either by virtue of the method throwing the exception itself or because it fails to catch such exceptions that a method it calls may throw.

88. If a class is declared without any access modifiers, where may the class be accessed?

A class that is declared without any access modifiers is said to have package or friendly access. This means that the class can only be accessed by other classes and interfaces that are defined within the same package.

89. What is the Map interface?

The Map interface replaces the JDK 1.1 Dictionary class and is used associate keys with values.

90. Does a class inherit the constructors of its super class?

A class does not inherit constructors from any of its super classes.

91. Name primitive Java types.

The primitive types are byte, char, short, int, long, float, double, and boolean.

92. Which class should you use to obtain design information about an object?

The Class class is used to obtain information about an object's design.

92. How can a GUI component handle its own events?

Page 193: C Questions

A component can handle its own events by implementing the required event-listener interface and adding itself as its own event listener.

93. How are the elements of a GridBagLayout organized?

The elements of a GridBagLayout are organized according to a grid. However, the elements are of different sizes and may occupy more than one row or column of the grid. In addition, the rows and columns may have different sizes.

94. What advantage do Java's layout managers provide over traditional windowing systems?

Java uses layout managers to lay out components in a consistent manner across all windowing platforms. Since Java's layout managers aren't tied to absolute sizing and positioning, they are able to accommodate platform-specific differences among windowing systems.

95. What are the problems faced by Java programmers who don't use layout managers?

Without layout managers, Java programmers are faced with determining how their GUI will be displayed across multiple windowing systems and finding a common sizing and positioning that will work within the constraints imposed by each windowing system.

96. What is the difference between static and non-static variables?

A static variable is associated with the class as a whole rather than with specific instances of a class. Non-static variables take on unique values with each object instance.

97. What is the difference between the paint() and repaint() methods?

The paint() method supports painting via a Graphics object. The repaint() method is used to cause paint() to be invoked by the AWT painting thread.

98. What is the purpose of the File class?

The File class is used to create objects that provide access to the files and directories of a local file system.

99. What restrictions are placed on method overloading?

Page 194: C Questions

Two methods may not have the same name and argument list but different return types.

100. What restrictions are placed on method overriding?

Overridden methods must have the same name, argument list, and return type. The overriding method may not limit the access of the method it overrides. The overriding method may not throw any exceptions that may not be thrown by the overridden method.

101. What is casting?

There are two types of casting, casting between primitive numeric types and casting between object

references. Casting between numeric types is used to convert larger values, such as double values,

to smaller values, such as byte values. Casting between object references is used to refer to an

object by a compatible class, interface, or array type reference.

102. Name Container classes.

Window, Frame, Dialog, FileDialog, Panel, Applet, or ScrollPane

103. What class allows you to read objects directly from a stream?

The ObjectInputStream class supports the reading of objects from input streams.

104. How are this() and super() used with constructors?

this() is used to invoke a constructor of the same class. super() is used to invoke a superclass

constructor.

105. How is it possible for two String objects with identical values not to be equal under

the == operator? How are this() and super() used with constructors?

The == operator compares two objects to determine if they are the same objects in memory. It is

possible for two String objects to have the same value, but located in different areas of memory.

106. What is an IO filter?

An IO filter is an object that reads from one stream and writes to another, usually altering the data in

some way as it is passed from one stream to another.

Page 195: C Questions

107. What is the Set interface?

The Set interface provides methods for accessing the elements of a finite mathematical set. Sets do

not allow duplicate elements.

108. What is the List interface?

The List interface provides support for ordered collections of objects.

109. What is the purpose of the enableEvents() method?

The enableEvents() method is used to enable an event for a particular object. Normally, an event is

enabled when a listener is added to an object for a particular event. The enableEvents() method is

used by objects that handle events by overriding their event-dispatch methods.

110. What is the difference between the File and RandomAccessFile classes?

The File class encapsulates the files and directories of the local file system. The RandomAccessFile

class provides the methods needed to directly access data contained in any part of a file.

111. What interface must an object implement before it can be written to a stream as an

object?

An object must implement the Serializable or Externalizable interface before it can be written to a

stream as an object.

112. What is the ResourceBundle class?

The ResourceBundle class is used to store locale-specific resources that can be loaded by a program

to tailor the program's appearance to the particular locale in which it is being run.

113. What is the difference between a Scrollbar and a ScrollPane?

A Scrollbar is a Component, but not a Container. A ScrollPane is a Container. A ScrollPane handles its

own events and performs its own scrolling.

114. What is a Java package and how is it used?

A Java package is a naming context for classes and interfaces. A package is used to create a

separate name space for groups of classes and interfaces. Packages are also used to organize

Page 196: C Questions

related classes and interfaces into a single API unit and to control accessibility to these classes and

interfaces.

115. What are the Object and Class classes used for?

The Object class is the highest-level class in the Java class hierarchy. The Class class is used to

represent the classes and interfaces that are loaded by a Java program.

116. 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.

117. What is tunnelling?

Tunnelling is a route to somewhere. For example, RMI tunnelling is a way to make RMI application

get through firewall. In CS world, tunnelling means a way to transfer data.

118. Does the code in finally block get executed if there is an exception and a return

statement in a catch block?

If an exception occurs and there is a return statement in catch block, the finally block is still

executed. The finally block will not be executed when the System.exit(1) statement is executed

earlier or the system shut down earlier or the memory is used up earlier before the thread goes to

finally block.

119. 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.

120. Is Java a super set of JavaScript?

No. They are completely different. Some syntax may be similar.

121. What is a Container in a GUI?

A Container contains and arranges other components (including other containers) through the use of

layout managers, which use specific layout policies to determine where components should go as a

function of the size of the container.

Page 197: C Questions

122. How the object oriented approach helps us keep complexity of software

development under control?

We can discuss such issue from the following aspects:

1. Objects allow procedures to be encapsulated with their data to reduce potential interference.

2. Inheritance allows well-tested procedures to be reused and enables changes to make once and

have effect in all relevant places.

3. The well-defined separations of interface and implementation allow constraints to be imposed on

inheriting classes while still allowing the flexibility of overriding and overloading.

123. What is polymorphism?

Polymorphism means "having many forms". It allows methods (may be variables) to be written that

needn't be concerned about the specifics of the objects they will be applied to. That is, the method

can be specified at a higher level of abstraction and can be counted on to work even on objects of

un-conceived classes.

124. What is design by contract?

The design by contract specifies the obligations of a method to any other methods that may use its

services and also theirs to it. For example, the preconditions specify what the method required to be

true when the method is called. Hence making sure that preconditions are. Similarly, postconditions

specify what must be true when the method is finished, thus the called method has the

responsibility of satisfying the post conditions.

In Java, the exception handling facilities support the use of design by contract, especially in the case

of checked exceptions. The assert keyword can be used to make such contracts.

125. What are use cases?

A use case describes a situation that a program might encounter and what behavior the program

should exhibit in that circumstance. It is part of the analysis of a program. The collection of use

cases should, ideally, anticipate all the standard circumstances and many of the extraordinary

circumstances possible so that the program will be robust.

126. What is scalability and performance?

Performance is a measure of "how fast can you perform this task." and scalability describes how an

application behaves as its workload and available computing resources increase.

Page 198: C Questions

127. What is the benefit of subclass?

Generally: The sub class inherits all the public methods and the implementation.

The sub class inherits all the protected methods and their implementation.

The sub class inherits all the default(non-access modifier) methods and their implementation.

The sub class also inherits all the public, protected and default member variables from the super

class.

The constructors are not part of this inheritance model.

128. How to add menushortcut to menu item?

If you have a button instance called aboutButton, you may add menu short cut by calling

aboutButton.setMnemonic('A'), so the user may be able to use Alt+A to click the button.

129. Where and how can you use a private constuctor.

Private constructor can be used if you do not want any other class to instanstiate it by using new.

The instantiation is done from a static public method, which is used when dealing with the factory

method pattern.

130. In System.out.println(),what is System,out and println,pls explain?

System is a predefined final class,out is a PrintStream object acting as a field member and println is

a built-in overloaded method in the out object.

131. What is meant by "Abstract Interface"?

First, an interface is abstract. That means you cannot have any implementation in an interface. All

the methods declared in an interface are abstract methods or signatures of the methods.

132. Can you make an instance of an abstract class? For example - java.util.Calender is

an abstract class with a method getInstance() which returns an instance of the Calender

class.

No! You cannot make an instance of an abstract class. An abstract class has to be sub-classed. If you

have an abstract class and you want to use a method which has been implemented, you may need

to subclass that abstract class, instantiate your subclass and then call that method.

133. What is the output of x > y? a:b = p*q when x=1,y=2,p=3,q=4?

Page 199: C Questions

When this kind of question has been asked, find the problems you think is necessary to ask back

before you give an answer. Ask if variables a and b have been declared or initialized. If the answer is

yes. You can say that the syntax is wrong. If the statement is rewritten as: x< y statement return

true and variable a is returned.

134. What is the difference between Swing and AWT components?

AWT components are heavy-weight, whereas Swing components are lightweight. Heavy weight

components depend on the local windowing toolkit. For example, java.awt.Button is a heavy weight

component, when it is running on the Java platform for Unix platform, it maps to a real Motif button.

135. Why Java does not support pointers?

Because pointers are unsafe. Java uses reference types to hide pointers and programmers feel

easier to deal with reference types without pointers. This is why Java and C-sharp shine.

136. Parsers? DOM vs SAX parser

Parsers are fundamental xml components, a bridge between XML documents and applications that

process that XML. The parser is responsible for handling xml syntax, checking the contents of the

document against constraints established in a DTD or Schema.

DOM

1. Tree of nodes

2. Memory: Occupies more memory, preffered for small XML documents

3. Slower at runtime

4. Stored as objects

5. Programmatically easy

6. Ease of navigation

SAX

1. Sequence of events

2. Doesn't use any memory preferred for large documents

3. Faster at runtime

4. Objects are to be created

5. Need to write code for creating objects

6. Backward navigation is not possible as it sequentially processes the document

137. Can you declare a class as private?

Page 200: C Questions

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

}

}

138. What is the difference between shallow copy and deep copy?

Shallow copy shares the same reference with the original object like cloning, whereas the deep copy

get a duplicate instance of the original object. If the shallow copy has been changed, the original

object will be reflected and vice versa.

139. Can one create a method which gets a String and modifies it?

No. In Java, Strings are constant or immutable; their values cannot be changed after they are

created, but they can be shared. Once you change a string, you actually create a new object. For

example:

String s = "abc"; //create a new String object representing "abc"

s = s.toUpperCase(); //create another object representing "ABC"

140. Why is multiple inheritance not possible in Java?

It depends on how you understand "inheritance". Java can only "extends" one super class, but can

"implements" many interfaces; that doesn't mean the multiple inheritance is not possible. You may

use interfaces to make inheritance work for you. Or you may need to work around. For example, if

you cannot get a feature from a class because your class has a super class already, you may get

that class's feature by declaring it as a member field or getting an instance of that class. So the

answer is that multiple inheritance in Java is possible.

141. Can Java code be compiled to machine dependent executable file?

Yes. There are many tools out there. If you did so, the generated exe file would be run in the specific

platform, not cross-platform.

Page 201: C Questions

142. What is the relationship between synchronized and volatile keyword?

The JVM is guaranteed to treat reads and writes of data of 32 bits or less as atomic.(Some JVM might

treat reads and writes of data of 64 bits or less as atomic in future) For long or double variable,

programmers should take care in multi-threading environment. Either put these variables in a

synchronized method or block, or declare them volatile.

143. This class (IncrementImpl) will be used by various threads concurrently; can you see

the inherent flaw(s)? How would you improve it?

public class IncrementImpl {

private static int counter = 0;

public synchronized void increment() {

counter++;

}

public int getCounter() {

return counter;

}

}

The counter is static variable which is shared by multiple instances of this class. The increment()

method is synchronized, but the getCounter() should be synchronized too. Otherwise the Java run-

time system will not guarantee the data integrity and the race conditions will occur. The famous

producer/consumer example listed at Sun's thread tutorial site will tell more.

one of solutions

public class IncrementImpl {

private static int counter = 0;

public synchronized void increment() {

counter++;

}

public synchronized int getCounter() {

return counter;

}

}

144. What are the drawbacks of inheritance?

Page 202: C Questions

Since inheritance inherits everything from the super class and interface, it may make the subclass

too clustering and sometimes error-prone when dynamic overriding or dynamic overloading in some

situation. In addition, the inheritance may make peers hardly understand your code if they don't

know how your super-class acts and add learning curve to the process of development.

Usually, when you want to use a functionality of a class, you may use subclass to inherit such

function or use an instance of this class in your class. Which is better, depends on your specification.

145. Is there any other way that you can achieve inheritance in Java?

There are a couple of ways. As you know, the straight way is to "extends" and/or "implements". The

other way is to get an instance of the class to achieve the inheritance. That means to make the

supposed-super-class be a field member. When you use an instance of the class, actually you get

every function available from this class, but you may lose the dynamic features of OOP

146. Two methods have key words static synchronized and synchronized separately.

What is the difference between them?

Both are synchronized methods. One is instance method, the other is class method. Method with

static modifier is a class method. That means the method belongs to class itself and can be

accessed directly with class name and is also called Singleton design. The method without static

modifier is an instance method. That means the instance method belongs to its object. Every

instance of the class gets its own copy of its instance method.

When synchronized is used with a static method, a lock for the entire class is obtained. When

synchronized is used with a non-static method, a lock for the particular object (that means instance)

of the class is obtained.

Since both methods are synchronized methods, you are not asked to explain what is a synchronized

method. You are asked to tell the difference between instance and class method. Of course, your

explanation to how synchronized keyword works doesn't hurt. And you may use this opportunity to

show your knowledge scope.

147. 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)

Page 203: C Questions

6. unmodifiableSortedSet(SortedSet s)

If you get an Iterator from one of these unmodifiable collections, when you call remove(), it will

throw an UnsupportedOperationException.

148. Can a private method of a superclass be declared within a subclass?

Sure. A private field or method or inner class belongs to its declared class and hides from its

subclasses. There is no way for private stuff to have a runtime overloading or overriding

(polymorphism) features.

149. Why Java does not support multiple inheritance ?

This is a classic question. Yes or No depends on how you look at Java. If you focus on the syntax of

"extends" and compare with C++, you may answer 'No' and give explanation to support you. Or you

may answer 'Yes'. Recommend you to say 'Yes'.

Java DOES support multiple inheritance via interface implementation. Some people may not think in

this way. Give explanation to support your point.

150. What is the difference between final, finally and finalize?

Short answer:

final - declares constant

finally - relates with exception handling

finalize - helps in garbage collection

If asked to give details, explain:

final field, final method, final class

try/finally, try/catch/finally

protected void finalize() in Object class

151. What kind of security tools are available in J2SE 5.0?

There are three tools that can be used to protect application working within the scope of security

policies set at remote sites.

keytool -- used to manage keystores and certificates.

jarsigner -- used to generate and verify JAR signatures.

policytool -- used for managing policy files.

There are three tools that help obtain, list and manage Kerberos tickets.

kinit -- used to obtain Kerberos V5 tickets.

Page 204: C Questions

tklist -- used to list entries in credential cache and key tab.

ktab -- used to help manage entries in the key table.

152. How to make an array copy from System?

There is a method called arraycopy in the System class. You can do it:

System.arraycopy(sourceArray, srcOffset, destinationArray, destOffset, numOfElements2Copy);

When you use this method, the destinationArray will be filled with the elements of sourceArray at

the length specified.

153. Can we use System.arraycopy() method to copy the same array?

Yes, you can. The source and destination arrays can be the same if you want to copy a subset of the

array to another area within that array.

154. What is shallow copy or shallow clone in array cloning?

Cloning an array invloves creating a new array of the same size and type and copying all the old

elements into the new array. But such copy is called shallow copy or shallow clone because any

changes to the object would be reflected in both arrays.

155. When is the ArrayStoreException thrown?

When copying elements between different arrays, if the source or destination arguments are not

arrays or their types are not compatible, an ArrayStoreException will be thrown.

156. How to check two arrays to see if contents have the same types and contain the

same elements?

One of options is to use the equals() method of Arrays class.

Arrays.equals(a, b);

If the array types are different, a compile-time error will happen.

157. Do not use the String contatenation operator in lengthy loops or other places where

performance could suffer. Is that true?

Yes.

158. What are the different types of inner classes?

Page 205: C Questions

There are four different types of inner classes in Java. They are: a)Static member classes , a static

member class has access to all static methods of the parent, or top-level, class b) Member classes,

the member class is instance specific and has access to any and all methods and members, even

the parent's this reference c) Local classes, are declared within a block of code and are visible only

within that block, just as any other method variable. d) Anonymous classes, is a local class that has

no name

159. In which case would you choose a static inner class?

Interesting one, static inner classes can access the outer class's protected and private fields. This is

both a positive and a negitive point for us since we can, in essence, violate the encapsulation of the

outer class by mucking up the outer class's protected and private fields. The only proper use of that

capability is to write white-box tests of the class -- since we can induce cases that might be very

hard to induce via normal black-box tests (which don't have access to the internal state of the

object). Second advantage,if I can say, is that, we can this static concept to impose restriction on

the inner class. Again as discussed in earlier point, an Inner class has access to all the public, private

and protected members of the parent class. Suppose you want to restrict the access even to inner

class, how would you go ahead? Making the inner class static enforces it to access only the public

static members of the outer class( Since, protected and private members are not supposed to be

static and that static members can access only other static members). If it has to access any non-

static member, it has to create an instance of the outer class which leads to accessing only public

members.

160. What is the differnce between final, finally and finalize?

final is used for making a class no-subclassable, and making a member variable as a constant which

cannot be modified. finally is usuall used to release all the resources utilized inside the try block. All

the resources present in the finalize method will be garbage collected whenever GC is called.

Though finally and finalize seem to be for a similar task there is an interesting tweak here, usually I

prefer finally than finalize unless it is unavoidable. This is because the code in finally block is

guranteed of execution irrespective of occurance of exception, while execution of finalize is not

guarenteed.finalize method is called by the garbage collector on an object when the garbage

collector determines that there are no more references to the object. Presumably the garbage

collector will, like its civil servant namesake, visit the heap on a regular basis to clean up resources

that are no longer in use. Garbage collection exists to prevent programmers from calling delete. This

is a wonderful feature. For example, if you can't call delete, then you can't accidentally call delete

twice on the same object. However, removing delete from the language is not the same thing as

Page 206: C Questions

automatically cleaning up. To add to it, Garbage collection might not ever run. If garbage collection

runs at all, and an object is no longer referenced, then that object's finalize will run. Also, across

multiple objects, finalize order is not predictable. The correct approach to resource cleanup in Java

language programs does not rely on finalize. Instead, you simply write explicit close methods for

objects that wrap native resources. If you take this approach, you must document that the close

method exists and when it should be called. Callers of the object must then remember to call close

when they are finished with a resource.

161. What is weak reference in Java

A weak reference is one that does not prevent the referenced object from being garbage collected.

You might use them to manage a HashMap to look up a cache of objects. A weak reference is a

reference that does not keep the object it refers to alive. A weak reference is not counted as a

reference in garbage collection. If the object is not referred to elsewhere as well, it will be garbage

collected.

162. What's the difference between the methods sleep() and wait()

The code sleep(1000); puts thread aside for exactly one second. The code wait(1000), causes a wait

of up to one second. A thread could stop waiting earlier if it receives the notify() or notifyAll() call.

The method wait() is defined in the class Object and the method sleep() is defined in the class

Thread.

163. The following statement prints true or false, why?

byte[] a = { 1, 2, 3 };,

byte[] b = (byte[]) a.clone();

System.out.println(a == b);

The false will be printed out. Because the two arrays have distinctive memory addresses. Starting in

Java 1.2, we can use java.util.Arrays.equals(a, b) to compare whether two arrays have the same

contents.

164. Why do we need to use getSystemResource() and getSystemResources() method to

load resources?

Because we want to look for resources strictly from the system classpath, These methods use the

system ClassLoader to locate resources, which gives you stricter control of the resources used by

the application.

Page 207: C Questions

165.ArithmeticException?

The ArithmeticException is thrown when integer is divided by zero or taking the remainder of a

number by zero. It is never thrown in floating-point operations.

166. What is a transient variable?

A transient variable is a variable that may not be serialized.

167. Which containers use a border Layout as their default layout?

The window, Frame and Dialog classes use a border layout as their default layout.

168. Why do threads block on I/O?

Threads block on I/O (that is enters the waiting state) so that other threads may execute while the

I/O Operation is performed.

169. What is the output from System.out.println("Hello"+null);?

Hellonull

170. What is synchronization and why is it important?

With respect to multithreading, synchronization is the capability to control the access of multiple

threads to shared resources. Without synchronization, it is possible for one thread to modify a

shared object while another thread is in the process of using or updating that object's value. This

often leads to significant errors.

171. Can a lock be acquired on a class?

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

172. What's new with the stop(), suspend() and resume() methods in JDK 1.2??

The stop(), suspend() and resume() methods have been deprecated in JDK 1.2.

173. Is null a keyword?

The null value is not a keyword.

174. What is the preferred size of a component?

Page 208: C Questions

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

display normally.

175. What method is used to specify a container's layout?

The setLayout() method is used to specify a container's layout.

176. Which containers use a FlowLayout as their default layout?

The Panel and Applet classes use the FlowLayout as their default layout.

177. What state does a thread enter when it terminates its processing?

When a thread terminates its processing, it enters the dead state.

178. What is the Collections API?

The Collections API is a set of classes and interfaces that support operations on collections of

objects.

179. which characters may be used as the second character of an identifier, but not as

the first character of an identifier?

The digits 0 through 9 may not be used as the first character of an identifier but they may be used

after the first character of an identifier.

180. What is the List interface?

The List interface provides support for ordered collections of objects.

181. How does Java handle integer overflows and underflows?

It uses those low order bytes of the result that can fit into the size of the type allowed by the

operation.

182. What is the Vector class?

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

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

A (non-local) inner class may be declared as public, protected, private, static, final, or abstract.

Page 209: C Questions

184. What is an Iterator interface?

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

185. What is the difference between the >> and >>> operators?

The >> operator carries the sign bit when shifting right. The >>> zero-fills bits that have been

shifted out.

186. Which method of the Component class is used to set the position and size of a

component?

setBounds()

187. How many bits are used to represent Unicode, ASCII, UTF-16, and UTF-8 characters?

Unicode requires 16 bits and ASCII require 7 bits. Although the ASCII character set uses only 7 bits, it

is usually represented as 8 bits. UTF-8 represents characters using 8, 16, and 18 bit patterns. UTF-16

uses 16-bit and larger bit patterns.

188. What is the difference between yielding and sleeping?

When a task invokes its yield() method, it returns to the ready state. When a task invokes its sleep()

method, it returns to the waiting state.

189. Which java.util classes and interfaces support event handling?

The EventObject class and the EventListener interface support event processing.

190. Is sizeof a keyword?

The sizeof operator is not a keyword.

191. What are wrapper classes?

Wrapper classes are classes that allow primitive types to be accessed as objects.

192. Does garbage collection guarantee that a program will not run out of memory?

Page 210: C Questions

Garbage collection does not guarantee that a program will not run out of memory. It is possible for

programs to use up memory resources faster than they are garbage collected. It is also possible for

programs to create objects that are not subject to garbage collection.

193. What restrictions are placed on the location of a package statement within a source

code file?

A package statement must appear as the first line in a source code file (excluding blank lines and

comments).

194. Can an object's finalize() method be invoked while it is reachable?

An object's finalize() method cannot be invoked by the garbage collector while the object is still

reachable. However, an object's finalize() method may be invoked by other objects.

195. What is the immediate superclass of the Applet class?

Panel

196. What is the difference between preemptive scheduling and time slicing?

Under preemptive scheduling, the highest priority task executes until it enters the waiting or dead

states or a higher priority task comes into existence. Under time slicing, a task executes for a

predefined slice of time and then reenters the pool of ready tasks. The scheduler then determines

which task should execute next, based on priority and other factors.

197. Name three Component subclasses that support painting.

The Canvas, Frame, Panel, and Applet classes support painting.

198. 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.

199. What is the immediate superclass of the Dialog class?

Window.

200. What is clipping?

Clipping is the process of confining paint operations to a limited area or shape.

Page 211: C Questions

201. What is a native method?

A native method is a method that is implemented in a language other than Java.

202. Can a for statement loop indefinitely?

Yes, a for statement can loop indefinitely. For example, consider the following: for(;;) ;

203. What are order of precedence and associativity, and how are they used?

Order of precedence determines the order in which operators are evaluated in expressions. Associatity determines whether an expression is evaluated left-to-right or right-to-left

204. When a thread blocks on I/O, what state does it enter?

A thread enters the waiting state when it blocks on I/O.

205. To what value is a variable of the String type automatically initialized?

The default value of a String type is null.

206. What is the catch or declare rule for method declarations?

If a checked exception may be thrown within the body of a method, the method must either catch the exception or declare it in its throws clause.

207. What is the difference between a MenuItem and a CheckboxMenuItem?

The CheckboxMenuItem class extends the MenuItem class to support a menu item that may be checked or unchecked.

208. What is a task's priority and how is it used in scheduling?

A task's priority is an integer value that identifies the relative order in which it should be executed with respect to other tasks. The scheduler attempts to schedule higher priority tasks before lower priority tasks.

Page 212: C Questions

209. 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.

210. 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.

211. Can an anonymous class be declared as implementing an interface and extending a class?

An anonymous class may implement an interface or extend a superclass, but may not be declared to do both.

212. What is the range of the short type?

The range of the short type is -(2^15) to 2^15 - 1.

213. What is the range of the char type?

The range of the char type is 0 to 2^16 - 1.

214. In which package are most of the AWT events that support the event-delegation model defined?

Most of the AWT-related events of the event-delegation model are defined in the java.awt.event package. The AWTEvent class is defined in the java.awt package.

215. What is the immediate superclass of Menu?

MenuItem

216. What is the purpose of finalization?

The purpose of finalization is to give an unreachable object the opportunity to perform any cleanup processing before the object is garbage collected.

217. Which class is the immediate superclass of the MenuComponent class.

Object

Page 213: C Questions

218. What invokes a thread's run() method?

After a thread is started, via its start() method or that of the Thread class, the JVM invokes the thread's run() method when the thread is initially executed.

219. What is the difference between the Boolean & operator and the && operator?

If an expression involving the Boolean & operator is evaluated, both operands are evaluated. Then the & operator is applied to the operand. When an expression involving the && operator is evaluated, the first operand is evaluated. If the first operand returns a value of true then the second operand is evaluated. The && operator is then applied to the first and second operands. If the first operand evaluates to false, the evaluation of the second operand is skipped.

220. Name three subclasses of the Component class.

Box.Filler, Button, Canvas, Checkbox, Choice, Container, Label, List, Scrollbar, or TextComponent

221. What is the GregorianCalendar class?

The GregorianCalendar provides support for traditional Western calendars.

222. Which Container method is used to cause a container to be laid out and redisplayed?

validate()

223. What is the purpose of the Runtime class?

The purpose of the Runtime class is to provide access to the Java runtime system.

224. How many times may an object's finalize() method be invoked by the garbage collector?

An object's finalize() method may only be invoked once by the garbage collector.

225. What is the purpose of the finally clause of a try-catch-finally statement? garbage collector?

Page 214: C Questions

The finally clause is used to provide the capability to execute code no matter whether or not an exception is thrown or caught.

226. What is the argument type of a program's main() method?

A program's main() method takes an argument of the String[] type.

227. Which Java operator is right associative?

The = operator is right associative.

228. What is the Locale class?

The Locale class is used to tailor program output to the conventions of a particular geographic, political, or cultural region.

229. Can a double value be cast to a byte?

Yes, a double value can be cast to a byte.

230. What is the difference between a break statement and a continue statement?

A break statement results in the termination of the statement to which it applies (switch, for, do, or while). A continue statement is used to end the current loop iteration and return control to the loop statement.

231. What must a class do to implement an interface?

It must provide all of the methods in the interface and identify the interface in its implements clause.

232. What method is invoked to cause an object to begin executing as a separate thread?

The start() method of the Thread class is invoked to cause an object to begin executing as a separate thread.

233. Name two subclasses of the TextComponent class.

TextField and TextArea

234. What is the advantage of the event-delegation model over the earlier event-inheritance model?

Page 215: C Questions

The event-delegation model has two advantages over the event-inheritance model. First, it enables event handling to be handled by objects other than the ones that generate the events (or their containers). This allows a clean separation between a component's design and its use. The other advantage of the event-delegation model is that it performs much better in applications where many events are generated. This performance improvement is due to the fact that the event-delegation model does not have to repeatedly process unhandled events, as is the case of the event-inheritance model.

235. Which containers may have a MenuBar?

Frame

236. How are commas used in the initialization and iteration parts of a for statement?

Commas are used to separate multiple statements within the initialization and iteration parts of a for statement.

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

The wait(),notify(), and notifyAll() methods are used to provide an efficient way for threads to wait for a shared resource. When a thread executes an object's wait() method, it enters the waiting state. It only enters the ready state after another thread invokes the object's notify() or notifyAll() methods.

238. What is an abstract method?

An abstract method is a method whose implementation is deferred to a subclass.

239. How are Java source code files named?

A Java source code file takes the name of a public class or interface that is defined within the file. A source code file may contain at most one public class or interface. If a public class or interface is defined within a source code file, then the source code file must take the name of the public class or interface. If no public class or interface is defined within a source code file, then the file must take on a name that is different than its classes and interfaces. Source code files use the .java extension.

Page 216: C Questions

240. 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.

241. What are the high-level thread states?

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

242. 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.

243. Can a Byte object be cast to a double value?

No, an object cannot be cast to a primitive value.

244. What is the difference between a static and a non-static inner class?

A non-static inner class may have object instances that are associated with instances of the class's outer class. A static inner class does not have any object instances.

245. What is the difference between the String and StringBuffer classes?

String objects are constants. StringBuffer objects are not.

246. 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.

247. What is an object's lock and which objects have locks?

An object's lock is a mechanism that is used by multiple threads to obtain synchronized access to the object. A thread may execute a synchronized method of an object only after it has acquired the object's lock. All objects and classes have locks. A class's lock is acquired on the class's Class object.

248. What is the Dictionary class?

Page 217: C Questions

The Dictionary class provides the capability to store key-value pairs.

249. 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.

250. What is the % operator?

It is referred to as the modulo or remainder operator. It returns the remainder of dividing the first operand by the second operand.

Only Questions:

1. What are the differences between a List and a Set? 2. What are value objects and how are they used with EJBs? 3. How do you code a Singleton in Java? 4. Diffrence between JRE And JVM AND JDK 5. What's a dynamic proxy class? 6. When should you call SwingUtilities.invokeLater()? 7. What are the differences between a Session Bean and an Entity Bean? 8. How do you read an XML file in Java? 9. Give an example of the Decorator pattern in the Java API. 10. Difference between an abstract class and interface 11. Inner classes 12. Difference between an inner class and a normal class 13. What is Entity Bean and Session Bean ? 14. What are the methods of Entity Bean? 15. How does Stateful Session bean store its state ? 16. Why does Stateless Session bean not store its state even though it has ejbActivate and ejbPassivate ? 17. What are the services provided by the container ? 18. Types of transaction ? 19. What is bean managed transaction ? 20. Why does EJB needs two interface( Home and Remote Interface) ? 21. What are transaction attributes ? 22. What is the difference between Container managed persistent bean and Bean managed persistent entity bean ? 23. What is J2EE ? 24. What is JTS ? 25. How many entity beans used and how many tables can u use in EJB project ? 26. What is scalable,portability in J2EE? 27. What is Connection pooling?Is it advantageous? 28. Method and class used for Connection pooling ?

Page 218: C Questions

29. How to deploy in J2EE(i.e Jar,War file) ? 30. How is entity bean created using Container managed entity bean ? 31. Sotware architechture of EJB ? 32. In Entity bean will the create method in EJB home and ejbCreate in Entity bean have the same parameters ? 33. What methods do u use in Servlet - Applet communication ? 34. What are the types of Servlet ? 35. Difference between HttpServlet and Generic Servlets ? 36. Difference between doGet and doPost ? 37. What are the methods in HttpServlet? 38. What are the types of SessionTracking? 39. What is Cookie ? Why is Cookie used ? 40. If my browser does not support Cookie,and my server sends a cookie instance What will happen ? 41. Why do u use Session Tracking in HttpServlet ? 42. Can u use javaScript in Servlets ? 43. What is the capacity the doGet can send to the server ? 44. What are the type of protocols used in HttpServlet ? 45. Difference between TCP/IP and IP protocol ? 46. Why do you use UniCastRemoteObject in RMI ? 47. How many interfaces are used in RMI? 48. Can Rmi registry be written in the code, without having to write it in the command prompt and if yes where? 49. Why is Socket used ? 50. What are the types of JDBC drivers ? 51. Explain the third driver(Native protocol driver) ? 52. Which among the four driver is pure Java driver ? 53. What are the Isolation level in JDBC transaction ? 54. How do you connect with the database ? 55. How do you connect without the Class.forName (" ") ? 56. What does Class.forName return ? 57. What are the types of statement ? 58. Why is preparedStatement,CallableStatement used for? 59. In real time project which driver did u use ? 60. Difference between AWT and Swing compenents ? 61. Is there any heavy weight component in Swings ? 62. Can the Swing application if you upload in net, be compatible with your browser? 63. What should you do get your browser compatible with swing components? 64. What are the methods in Applet ? 65. When is init(),start() called ? 66. When you navigate from one applet to another what are the methods called ? 67. What is the difference between Trusted and Untrusted Applet ? 68. What is Exception ?

Page 219: C Questions

69. What are the ways you can handle exception ? 70. When is try,catch block used ? 71. What is finally method in Exceptions ? 72. What are the types of access modifiers ? 73. What is protected and friendly ? 74. What are the other modifiers ? 75. Is synchronised modifier ?