Play and learn 300 000+ tabs online
Showing posts with label Interview Questions. Show all posts
Showing posts with label Interview Questions. Show all posts

Thursday, May 27, 2010

C C++ interview 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.

What is the difference between realloc() and free()?
The free subroutine frees a block of memory previously allocated by the malloc subroutine. Undefined results occur if the Pointer parameter is not a valid pointer. If the Pointer parameter is a null value, no action will occur. The realloc subroutine changes the size of the block of memory pointed to by the Pointer parameter to the number of bytes specified by the Size parameter and returns a new pointer to the block. The pointer specified by the Pointer parameter must have been created with the malloc, calloc, or realloc subroutines and not been deallocated with the free or realloc subroutines. Undefined results occur if the Pointer parameter is not a valid pointer.

What is function overloading and operator overloading?
Function overloading: C++ enables several functions of the same name to be defined, as long as these functions have different sets of parameters (at least as far as their types are concerned). This capability is called function overloading. When an overloaded function is called, the C++ compiler selects the proper function by examining the number, types and order of the arguments in the call. Function overloading is commonly used to create several functions of the same name that perform similar tasks but on different data types.

Operator overloading allows existing C++ operators to be redefined so that they work on objects of user-defined classes. Overloaded operators are syntactic sugar for equivalent function calls. They form a pleasant facade that doesn't add anything fundamental to the language (but they can improve understandability and reduce maintenance costs).

What is the difference between declaration and definition?
The declaration tells the compiler that at some later point we plan to present the definition of this declaration.
E.g.: void stars () //function declaration
The definition contains the actual implementation.
E.g.: void stars () // declarator
{
for(int j=10; j > =0; j--) //function body
cout << *;
cout <<>

What are the advantages of inheritance?
It permits code reusability. Reusability saves time in program development. It encourages the reuse of proven and debugged high-quality software, thus reducing problem after a system becomes functional.

How do you write a function that can reverse a linked-list?
void reverselist(void)
{
if(head==0)
return;
if(head->next==0)
return;
if(head->next==tail)
{
head->next = 0;
tail->next = head;
}
else
{
node* pre = head;
node* cur = head->next;
node* curnext = cur->next;
head->next = 0;
cur-> next = head;

for(; curnext!=0; )
{
cur->next = pre;
pre = cur;
cur = curnext;
curnext = curnext->next;
}
curnext->next = cur;
}
}

What do you mean by inline function?
The idea behind inline functions is to insert the code of a called function at the point where the function is called. If done carefully, this can improve the application's performance in exchange for increased compile time and possibly (but not always) an increase in the size of the generated binary executables.


Write a program that ask for user input from 5 to 9 then calculate the average
#include "iostream.h"
int main() {
int MAX = 4;
int total = 0;
int average;
int numb;
for (int i=0; icout << "Please enter your input between 5 and 9: ";
cin >> numb;
while ( numb<5>9) {
cout << "Invalid input, please re-enter: ";
cin >> numb;
}
total = total + numb;
}
average = total/MAX;
cout << "The average number is: " <<>return 0;
}

What is public, protected, private?
•    Public, protected and private are three access specifiers in C++.
•    Public data members and member functions are accessible outside the class.
•    Protected data members and member functions are only available to derived classes.
•    Private data members and member functions can’t be accessed outside the class. However there is an exception can be using friend classes.
Write a function that swaps the values of two integers, using int* as the argument type.
void swap(int* a, int*b) {
int t;
t = *a;
*a = *b;
*b = t;
}

Tell how to check whether a linked list is circular.

Create two pointers, each set to the start of the list. Update each as follows:
while (pointer1) {
pointer1 = pointer1->next;
pointer2 = pointer2->next; if (pointer2) pointer2=pointer2->next;
if (pointer1 == pointer2) {
print (\"circular\n\");
}
}

OK, why does this work?
If a list is circular, at some point pointer2 will wrap around and be either at the item just before pointer1, or the item before that. Either way, it’s either 1 or 2 jumps until they meet.

What is 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.

What is virtual constructors/destructors?

Answer1
Virtual destructors:
If an object (with a non-virtual destructor) is destroyed explicitly by applying the delete operator to a base-class pointer to the object, the base-class destructor function (matching the pointer type) is called on the object.
There is a simple solution to this problem declare a virtual base-class destructor.
This makes all derived-class destructors virtual even though they don’t have the same name as the base-class destructor. Now, if the object in the hierarchy is destroyed explicitly by applying the delete operator to a base-class pointer to a derived-class object, the destructor for the appropriate class is called. Virtual constructor: Constructors cannot be virtual. Declaring a constructor as a virtual function is a syntax error.

Answer2
Virtual destructors: If an object (with a non-virtual destructor) is destroyed explicitly by applying the delete operator to a base-class pointer to the object, the base-class destructor function (matching the pointer type) is called on the object.
There is a simple solution to this problem – declare a virtual base-class destructor. This makes all derived-class destructors virtual even though they don’t have the same name as the base-class destructor. Now, if the object in the hierarchy is destroyed explicitly by applying the delete operator to a base-class pointer to a derived-class object, the destructor for the appropriate class is called.

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

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

What are the advantages of inheritance?
• It permits code reusability.
• Reusability saves time in program development.
• It encourages the reuse of proven and debugged high-quality software, thus reducing problem after a system becomes functional.
What is the difference between declaration and definition?
The declaration tells the compiler that at some later point we plan to present the definition of this declaration.
E.g.: void stars () //function declaration
The definition contains the actual implementation.
E.g.: void stars () // declarator
{
for(int j=10; j>=0; j--) //function body
cout<<”*”;
cout<
What is the difference between an ARRAY and a LIST?

Answer1
Array is collection of homogeneous elements.
List is collection of heterogeneous elements.

For Array memory allocated is static and continuous.
For List memory allocated is dynamic and Random.

Array: User need not have to keep in track of next memory allocation.
List: User has to keep in Track of next location where memory is allocated.

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

//With Array you have direct access to memory position 5
Object x = a[5]; // x takes directly a reference to 5th element of array

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

for( it = list.begin() ; it != list.end() ; it++ )
{
if( i==5)
{
x = *it;
break;
}
i++;
}

What is a template?
Templates allow to create generic functions that admit any data type as parameters and return value without having to overload the function with all the possible data types. Until certain point they fulfill the functionality of a macro. Its prototype is any of the two following ones:

template function_declaration; template function_declaration;

The only difference between both prototypes is the use of keyword class or typename, its use is indistinct since both expressions have exactly the same meaning and behave exactly the same way.

You have two pairs: new() and delete() and another pair : alloc() and free(). Explain differences between eg. new() and malloc()

Answer1
1.) “new and delete” are preprocessors while “malloc() and free()” are functions. [we dont use brackets will calling new or delete].
2.) no need of allocate the memory while using “new” but in “malloc()” we have to use “sizeof()”.
3.) “new” will initlize the new memory to 0 but “malloc()” gives random value in the new alloted memory location [better to use calloc()]

Answer2
new() allocates continous space for the object instace
malloc() allocates distributed space.
new() is castless, meaning that allocates memory for this specific type,
malloc(), calloc() allocate space for void * that is cated to the specific class type pointer.

What is the difference between class and structure?

Structure: Initially (in C) a structure was used to bundle different type of data types together to perform a particular functionality. But C++ extended the structure to contain functions also. The major difference is that all declarations inside a structure are by default public.
Class: Class is a successor of Structure. By default all the members inside the class are private.

What is RTTI?

Runtime type identification (RTTI) lets you find the dynamic type of an object when you have only a pointer or a reference to the base type. RTTI is the official way in standard C++ to discover the type of an object and to convert the type of a pointer or reference (that is, dynamic typing). The need came from practical experience with C++. RTTI replaces many homegrown versions with a solid, consistent approach.

What is encapsulation?

Packaging an object’s variables within its methods is called encapsulation.

Explain term POLIMORPHISM and give an example using eg. SHAPE object: If I have a base class SHAPE, how would I define DRAW methods for two objects CIRCLE and SQUARE

Answer1
POLYMORPHISM : A phenomenon which enables an object to react differently to the same function call.
in C++ it is attained by using a keyword virtual

Example
public class SHAPE
{
public virtual void SHAPE::DRAW()=0;
}
Note here the function DRAW() is pure virtual which means the sub classes must implement the DRAW() method and SHAPE cannot be instatiated

public class CIRCLE::public SHAPE
{
public void CIRCLE::DRAW()
{
// TODO drawing circle
}
}
public class SQUARE::public SHAPE
{
public void SQUARE::DRAW()
{
// TODO drawing square
}
}
now from the user class the calls would be like
globally
SHAPE *newShape;

When user action is to draw
public void MENU::OnClickDrawCircle(){
newShape = new CIRCLE();
}

public void MENU::OnClickDrawCircle(){
newShape = new SQUARE();
}

the when user actually draws
public void CANVAS::OnMouseOperations(){
newShape->DRAW();
}

Answer2
class SHAPE{
public virtual Draw() = 0; //abstract class with a pure virtual method
};

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

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

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

What is an object?

Object is a software bundle of variables and related methods. Objects have state and behavior.

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

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

Describe PRIVATE, PROTECTED and PUBLIC – the differences and give examples.

class Point2D{
int x; int y;
public int color;
protected bool pinned;
public Point2D() : x(0) , y(0) {} //default (no argument) constructor
};
Point2D MyPoint;
You cannot directly access private data members when they are declared (implicitly) private:
MyPoint.x = 5; // Compiler will issue a compile ERROR
//Nor yoy can see them:
int x_dim = MyPoint.x; // Compiler will issue a compile ERROR
On the other hand, you can assign and read the public data members:
MyPoint.color = 255; // no problem
int col = MyPoint.color; // no problem
With protected data members you can read them but not write them: MyPoint.pinned = true; // Compiler will issue a compile ERROR
bool isPinned = MyPoint.pinned; // no problem

What is namespace?

Namespaces allow us to group a set of global classes, objects and/or functions under a name. To say it somehow, they serve to split the global scope in sub-scopes known as namespaces.
The form to use namespaces is:
namespace identifier { namespace-body }
Where identifier is any valid identifier and namespace-body is the set of classes, objects and functions that are included within the namespace. For example:
namespace general { int a, b; } In this case, a and b are normal variables integrated within the general namespace. In order to access to these variables from outside the namespace we have to use the scope operator ::. For example, to access the previous variables we would have to put:
general::a general::b
The functionality of namespaces is specially useful in case that there is a possibility that a global object or function can have the same name than another one, causing a redefinition error.

What do you mean by inheritance?

Inheritance is the process of creating new classes, called derived classes, from existing classes or base classes. The derived class inherits all the capabilities of the base class, but can add embellishments and refinements of its own.

What is a COPY CONSTRUCTOR and when is it called?

A copy constructor is a method that accepts an object of the same class and copies it’s data members to the object on the left part of assignement:
class Point2D{
int x; int y;
public int color;
protected bool pinned;
public Point2D() : x(0) , y(0) {} //default (no argument) constructor
public Point2D( const Point2D & ) ;
};
Point2D::Point2D( const Point2D & p )
{
this->x = p.x;
this->y = p.y;
this->color = p.color;
this->pinned = p.pinned;
}
main(){
Point2D MyPoint;
MyPoint.color = 345;
Point2D AnotherPoint = Point2D( MyPoint ); // now AnotherPoint has color = 345

What is Boyce Codd Normal form?

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

What is virtual class and friend class?

Friend classes are used when two or more classes are designed to work together and need access to each other's implementation in ways that the rest of the world shouldn't be allowed to have. In other words, they help keep private things private. For instance, it may be desirable for class DatabaseCursor to have more privilege to the internals of class Database than main() has.

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

virtual

What do you mean by binding of data and functions?

Encapsulation.

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

1.Taking a reference to the function from the DLL instance.
2. Using the DLL ’s Type Library.



What is the difference between an object and a class?

Classes and objects are separate but related concepts. Every object belongs to a class and every class contains one or more related objects.
- A Class is static. All of the attributes of a class are fixed before, during, and after the execution of a program. The attributes of a class don't change.
- The class to which an object belongs is also (usually) static. If a particular object belongs to a certain class at the time that it is created then it almost certainly will still belong to that class right up until the time that it is destroyed.
- An Object on the other hand has a limited lifespan. Objects are created and eventually destroyed. Also during that lifetime, the attributes of the object may undergo significant change.

Suppose that data is an array of 1000 integers. Write a single function call that will sort the 100 elements data [222] through data [321].

quicksort ((data + 222), 100);

What is a class?

Class is a user-defined data type in C++. It can be created to solve a particular kind of problem. After creation the user need not know the specifics of the working of a class.

What is friend function?

As the name suggests, the function acts as a friend to a class. As a friend of a class, it can access its private and protected members. A friend function is not a member of the class. But it must be listed in the class definition.

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

Mergesort always makes recursive calls to sort subarrays that are about half size of the original array, resulting in O(n log n) time.

What is abstraction?

Abstraction is of the process of hiding unwanted details from the user.

What are virtual functions?

A virtual function allows derived classes to replace the implementation provided by the base class. The compiler makes sure the replacement is always called whenever the object in question is actually of the derived class, even if the object is accessed by a base pointer rather than a derived pointer. This allows algorithms in the base class to be replaced in the derived class, even if users don't know about the derived class.

What is the difference between an external iterator and an internal iterator? Describe an advantage of an external iterator.

An internal iterator is implemented with member functions of the class that has items to step through. .An external iterator is implemented as a separate class that can be "attach" to the object that has items to step through. .An external iterator has the advantage that many difference iterators can be active simultaneously on the same object.

What is a scope resolution operator?

A scope resolution operator (::), can be used to define the member functions of a class outside the class.

What do you mean by pure virtual functions?

A pure virtual member function is a member function that the base class forces derived classes to provide. Normally these member functions have no implementation. Pure virtual functions are equated to zero.

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

What is polymorphism? Explain with an example?

"Poly" means "many" and "morph" means "form". Polymorphism is the ability of an object (or reference) to assume (be replaced by) or become many different forms of object.
Example: function overloading, function overriding, virtual functions. Another example can be a plus ‘+’ sign, used for adding two integers or for using it to concatenate two strings.

How can you quickly find the number of elements stored in a a) static array b) dynamic array ?
Why is it difficult to store linked list in an array?
How can you find the nodes with repetetive data in a linked list?

Write a prog to accept a given string in any order and flash error if any of the character is different. For example : If abc is the input then abc, bca, cba, cab bac are acceptable but aac or bcd are unacceptable.
Write out a function that prints out all the permutations of a string. For example, abc would give you abc, acb, bac, bca, cab, cba. You can assume that all the characters will be unique.

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

#include
main()
{
typedef union
{
int a;
char b[10];
float c;
}
Union;
Union x,y = {100};
x.a = 50;
strcpy(x.b,\"hello\");
x.c = 21.50;
printf(\"Union x : %d %s %f \n\",x.a,x.b,x.c );
printf(\"Union y :%d %s%f \n\",y.a,y.b,y.c);
}
Given inputs X, Y, Z and operations | and & (meaning bitwise OR and AND, respectively)
What is output equal to in

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

Why are arrays usually processed with for loop?

The real power of arrays comes from their facility of using an index variable to traverse the array, accessing each element with the same expression a[i]. All the is needed to make this work is a iterated statement in which the variable i serves as a counter, incrementing from 0 to a.length -1. That is exactly what a loop does.

What is an HTML tag?

An HTML tag is a syntactical construct in the HTML language that abbreviates specific instructions to be executed when the HTML script is loaded into a Web browser. It is like a method in Java, a function in C++, a procedure in Pascal, or a subroutine in FORTRAN.

What problems might the following macro bring to the application?

#define sq(x) x*x

Anything wrong with this code?
T *p = new T[10];
delete p;

Everything is correct, Only the first element of the array will be deleted”, The entire array will be deleted, but only the first element destructor will be called.

Anything wrong with this code?
T *p = 0;
delete p;

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

How do you decide which integer type to use?

It depends on our requirement. When we are required an integer to be stored in 1 byte (means less than or equal to 255) we use short int, for 2 bytes we use int, for 8 bytes we use long int.
A char is for 1-byte integers, a short is for 2-byte integers, an int is generally a 2-byte or 4-byte integer (though not necessarily), a long is a 4-byte integer, and a long long is a 8-byte integer.

What’s the best way to declare and define global variables?

The best way to declare global variables is to declare them after including all the files so that it can be used in all the functions.

What does extern mean in a function declaration?

Using extern in a function declaration we can make a function such that it can used outside the file in which it is defined.
An extern variable, function definition, or declaration also makes the described variable or function usable by the succeeding part of the current source file. This declaration does not replace the definition. The declaration is used to describe the variable that is externally defined.
If a declaration for an identifier already exists at file scope, any extern declaration of the same identifier found within a block refers to that same object. If no other declaration for the identifier exists at file scope, the identifier has external linkage.

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

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

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

In the first case 6 bytes are allocated to the variable a which is fixed, where as in the second case if *p is assigned to some other value the allocate memory can change.

What’s the auto keyword good for?

Answer1
Not much. It declares an object with automatic storage duration. Which means the object will be destroyed at the end of the objects scope. All variables in functions that are not declared as static and not dynamically allocated have automatic storage duration by default.
For example
int main()
{
int a; //this is the same as writing “auto int a;”
}

Answer2
Local variables occur within a scope; they are “local” to a function. They are often called automatic variables because they automatically come into being when the scope is entered and automatically go away when the scope closes. The keyword auto makes this explicit, but local variables default to auto auto auto auto so it is never necessary to declare something as an auto auto auto auto.

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

Answer1
a[] = “string”;
char *p = “string”;

The difference is this:
p is pointing to a constant string, you can never safely say
p[3]=’x';
however you can always say a[3]=’x';
char a[]=”string”; - character array initialization.
char *p=”string” ; - non-const pointer to a const-string.( this is permitted only in the case of char pointer in C++ to preserve backward compatibility with C.)

Answer2
a[] = “string”;
char *p = “string”;
a[] will have 7 bytes. However, p is only 4 bytes. P is pointing to an adress is either BSS or the data section (depending on which compiler — GNU for the former and CC for the latter).

Answer3
char a[] = “string”;
char *p = “string”;

for char a[]…….using the array notation 7 bytes of storage in the static memory block are taken up, one for each character and one for the terminating nul character.
But, in the pointer notation char *p………….the same 7 bytes required, plus N bytes to store the pointer variable “p” (where N depends on the system but is usually a minimum of 2 bytes and can be 4 or more)……

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

Answer1
If you want the code to be even slightly readable, you will use typedefs.
typedef char* (*functiontype_one)(void);
typedef functiontype_one (*functiontype_two)(void);
functiontype_two myarray[N]; //assuming N is a const integral

Answer2
char* (* (*a[N])())()
Here a is that array. And according to question no function will not take any parameter value.

What does extern mean in a function declaration?

It tells the compiler that a variable or a function exists, even if the compiler hasn’t yet seen it in the file currently being compiled. This variable or function may be defined in another file or further down in the current file.

How do I initialize a pointer to a function?

This is the way to initialize a pointer to a function
void fun(int a)
{
}
void main()
{
void (*fp)(int);
fp=fun;
fp(1);
}

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

By using the extern "C" linkage specification around the C function declarations.

Explain the scope resolution operator.

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

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

The default member and base-class access specifiers are different.

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

Two.
There are two formats for initializers in C++ as shown in the example that follows. The first format uses the traditional C notation. The second format uses constructor notation.
int foo = 123;
int bar (123);


How does throwing and catching exceptions differ from using setjmp and longjmp?

The throw operation calls the destructors for automatic objects instantiated since entry to the try block.

What is a default constructor?

Default constructor WITH arguments class B { public: B (int m = 0) : n (m) {} int n; }; int main(int argc, char *argv[]) { B b; return 0; }

What is a conversion constructor?

A constructor that accepts one argument of a different type.

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

A copy constructor constructs a new object by using the content of the argument object. An overloaded assignment operator assigns the contents of an existing object to another existing object of the same class.

When should you use multiple inheritance?

There are three acceptable answers: "Never," "Rarely," and "When the problem domain cannot be accurately modeled any other way."

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

A specialized class "is" a specialization of another class and, therefore, has the ISA relationship with the other class. An Employee ISA Person. This relationship is best implemented with inheritance. Employee is derived from Person. A class may have an instance of another class. For example, an employee "has" a salary, therefore the Employee class has the HASA relationship with the Salary class. This relationship is best implemented by embedding an object of the Salary class in the Employee class.

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

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

What is a mutable member?

One that can be modified by the class even when the object of the class or the member function doing the modification is const.

What is an explicit constructor?

A conversion constructor declared with the explicit keyword. The compiler does not use an explicit constructor to implement an implied conversion of types. It’s purpose is reserved explicitly for construction.

What is the Standard Template Library (STL)?

A library of container templates approved by the ANSI committee for inclusion in the standard C++ specification.
A programmer who then launches into a discussion of the generic programming model, iterators, allocators, algorithms, and such, has a higher than average understanding of the new technology that STL brings to C++ programming.

Describe run-time type identification.

The ability to determine at run time the type of an object by using the typeid operator or the dynamic_cast operator.

What problem does the namespace feature solve?

Multiple providers of libraries might use common global identifiers causing a name collision when an application tries to link with two or more such libraries. The namespace feature surrounds a library’s external declarations with a unique namespace that eliminates the potential for those collisions.
This solution assumes that two library vendors don’t use the same namespace identifier, of course.

Are there any new intrinsic (built-in) data types?

Yes. The ANSI committee added the bool intrinsic type and its true and false value keywords.

Will the following program execute?
void main()
{
void *vptr = (void *) malloc(sizeof(void));
vptr++;
}

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

Answer2
It will not build as sizeof cannot be applied to void* ( error “Unknown size” )

Answer3
How can it execute if it won’t even compile? It needs to be int main, not void main. Also, cannot increment a void *.

Answer4
According to gcc compiler it won’t show any error, simply it executes. but in general we can’t do arthematic operation on void, and gives size of void as 1

Answer5
The program compiles in GNU C while giving a warning for “void main”. The program runs without a crash. sizeof(void) is “1? hence when vptr++, the address is incremented by 1.

Answer6
Regarding arguments about GCC, be aware that this is a C++ question, not C. So gcc will compile and execute, g++ cannot. g++ complains that the return type cannot be void and the argument of sizeof() cannot be void. It also reports that ISO C++ forbids incrementing a pointer of type ‘void*’.

Answer7
in C++
voidp.c: In function `int main()’:
voidp.c:4: error: invalid application of `sizeof’ to a void type
voidp.c:4: error: `malloc’ undeclared (first use this function)
voidp.c:4: error: (Each undeclared identifier is reported only once for each function it appears in.)
voidp.c:6: error: ISO C++ forbids incrementing a pointer of type `void*’
But in c, it work without problems

void main()
{
char *cptr = 0?2000;
long *lptr = 0?2000;
cptr++;
lptr++;
printf(” %x %x”, cptr, lptr);
}Will it execute or not?

Answer1
For Q2: As above, won’t compile because main must return int. Also, 0×2000 cannot be implicitly converted to a pointer (I assume you meant 0×2000 and not 0?2000.)

Answer2
Not Excute.
Compile with VC7 results following errors:
error C2440: ‘initializing’ : cannot convert from ‘int’ to ‘char *’
error C2440: ‘initializing’ : cannot convert from ‘int’ to ‘long *’
Not Excute if it is C++, but Excute in C.
The printout:
2001 2004

What is the difference between Mutex and Binary semaphore?

semaphore is used to synchronize processes. where as mutex is used to provide synchronization between threads running in the same process.

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

Overloading a method (or function) in C++ is the ability for functions of the same name to be defined as long as these methods have different signatures (different set of parameters). Method overriding is the ability of the inherited class rewriting the virtual method of the base class.

What methods can be overridden in Java?

In C++ terminology, all public methods in Java are virtual. Therefore, all Java methods can be overwritten in subclasses except those that are declared final, static, and private.

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

The defining traits of an object-oriented langauge are:
* encapsulation
* inheritance
* polymorphism

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

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

Assignment Operator - What is the diffrence between a "assignment operator" and a "copy constructor"?

Answer1.
In assignment operator, you are assigning a value to an existing object. But in copy constructor, you are creating a new object and then assigning a value to that object. For example:
complex c1,c2;
c1=c2; //this is assignment
complex c3=c2; //copy constructor

Answer2.
A copy constructor is used to initialize a newly declared variable from an existing variable. This makes a deep copy like assignment, but it is somewhat simpler:
There is no need to test to see if it is being initialized from itself.
There is no need to clean up (eg, delete) an existing value (there is none).
A reference to itself is not returned.

"mutable" Keyword - What is "mutable"?

Answer1.
"mutable" is a C++ keyword. When we declare const, none of its data members can change. When we want one of its members to change, we declare it as mutable.

Answer2.
A "mutable" keyword is useful when we want to force a "logical const" data member to have its value modified. A logical const can happen when we declare a data member as non-const, but we have a const member function attempting to modify that data member. For example:
class Dummy {
public:
bool isValid() const;
private:
mutable int size_ = 0;
mutable bool validStatus_ = FALSE;
// logical const issue resolved
};
bool Dummy::isValid() const
// data members become bitwise const
{
if (size > 10) {
validStatus_ = TRUE; // fine to assign
size = 0; // fine to assign
}
}

Answer2.
"mutable" keyword in C++ is used to specify that the member may be updated or modified even if it is member of constant object. Example:
class Animal {
private:
string name;
string food;
mutable int age;
public:
void set_age(int a);
};
void main() {
const Animal Tiger(Fulffy,'antelope,1);
Tiger.set_age(2);
// the age can be changed since its mutable
}

RTTI - What is RTTI?

Answer1.
RTTI stands for "Run Time Type Identification". In an inheritance hierarchy, we can find out the exact type of the objet of which it is member. It can be done by using:
1) dynamic id operator
2) typecast operator

Answer2.
RTTI is defined as follows: Run Time Type Information, a facility that allows an object to be queried at runtime to determine its type. One of the fundamental principles of object technology is polymorphism, which is the ability of an object to dynamically change at runtime.

STL Containers - What are the types of STL containers?

There are 3 types of STL containers:
1. Adaptive containers like queue, stack
2. Associative containers like set, map
3. Sequence containers like vector, deque

Virtual Destructor - What is the need for Virtual Destructor?

Destructors are declared as virtual because if do not declare it as virtual the base class destructor will be called before the derived class destructor and that will lead to memory leak because derived classs objects will not get freed.Destructors are declared virtual so as to bind objects to the methods at runtime so that appropriate destructor is called.

Differences of C and C++
Could you write a small program that will compile in C but not in C++?

In C, if you can a const variable e.g.
const int i = 2;
you can use this variable in other module as follows
extern const int i;
C compiler will not complain.

But for C++ compiler u must write
extern const int i = 2;
else error would be generated.

Bitwise Operations - Given inputs X, Y, Z and operations | and & (meaning bitwise OR and AND, respectively), what is output equal to in?
output = (X &amp; Y) | (X & Z) | (Y & Z);

DataStructure Interview Questions

1.) What is Heap data structure?

The binary heap data
structures is an array that can be viewed as a complete binary tree.
Each
node of the binary tree corresponds to an element of the array.
The
array is completely filled on all levels except possibly lowest.

2.)
What are the major data structures used in the following areas : RDBMS,
Network data model & Hierarchical data model?

1. RDBMS Array
(i.e. Array of structures)
2. Network data model Graph
3.
Hierarchical data model Trees

3.) Why is the isEmpty() member
method called?

The isEmpty() member method is called within the
dequeue process to determine if there is an item in the
queue to be
removed i.e. isEmpty() is called to decide whether the queue has at
least one element.
This method is called by the dequeue() method
before returning the front element.
What method is used to place a
value onto the top of a stack?
push() method, Push is the direction
that data is being added to the stack.
push() member method places a
value onto the top of a stack.

4.) What is Linked List ?

Linked
List is one of the fundamental data structures. It consists of a
sequence of? nodes,
each containing arbitrary data fields and one or
two (”links”) pointing to the next and/or previous nodes.
A linked
list is a self-referential datatype because it contains a pointer or
link to another data of the same type.
Linked lists permit insertion
and removal of nodes at any point in the list in constant time, but do
not allow random access.

5.) Difference between calloc and
malloc?

malloc: allocate n bytes calloc: allocate m times n bytes
initialized to 0

6.) How many parts are there in a declaration
statement?

There are two main parts, variable identifier and data
type and the third type is optional
which is type qualifier like
signed/unsigned.

7.) What is the difference bitween NULL AND VOID
pointer?

NULL can be value for pointer type variables. VOID is a
type identifier which has not size.
NULL and void are not same.
Example: void* ptr = NULL;
Core Dimension is a Dimension table which
is used dedicated for single fact table or Datamart.
Conform
Dimension is a Dimension table which is used across fact tables or
Datamarts.

8.) How can a node be inserted in the middle of a
linked list?

By repointing the previous and the next elements of
existing nodes to the new node. You can insert a
node in the middle
of a linked list by repointing the previous and the next elements of
existing nodes to the new node.

9.) What are the various kinds of
sorting techniques? Which is has best case?

Bubble sort Quick
sort Insertion sort Selection sort Merge sort Heap sort Among the
sorting algorithms quick sort is the best one

10.) Without using
/,% and * operators. write a function to divide a number by 3?

#include

#include
void main()
{
int i,n;
float
j=0;
clrscr();
printf("enter the no");
scanf("%d",&n);
for(i=n;i>2;i=i-3)
{
j=j+1;
if(i==4)
{
j=j+1.333333;
}
if(i==5)
{
j=j+1.666666;
}
printf("%f",j);
getch();
}

11.)
What is the use of fflush() function?

The function fflush forces
a write of all buffered data for the given output or update stream via
the stream's underlying write function.

12.) What is binary tree?

A
binary tree is a tree in which every node has exactly two links i.e
left and right link

13.) Which one is faster? A binary search of
an orderd set of elements in an array or a sequential search of the
elements.

Binary search is faster because we traverse the
elements by using the policy of Divide and Conquer. we compare the
key
element with the approximately center element, if it is smaller than it
search is applied in the smaller elements only otherwise
the search
is applied in the larger set of elements. its complexity is as we all
know is log n as compared to the sequential one
whose complexity is
n.

Sunday, May 16, 2010

Professionalism

Professionalism

Interviews are like anything else in life, they take practice to perfect. The job market is highly competitive so you should always maintain a high standard of professionalism. This is guaranteed to impress your potential employer, as it will show focus and maturity.

What is Professionalism?

Professionalism is: Presentation, Punctuality and Preparation.

Presentation: Presentation is not just the clothes you wear, but your general presentation during the interview. Dress for success, formal attire is the best option. Look the part and you will be more likely to get it. Body language such as eye contact and how you greet your interviewer are important. Shaking hands is a sign of confidence and respect so is making regular eye contact. Always be polite not just during the interview but to any one you may have contact with in the office or work environment.

Punctuality: Being on time is essential to a successful interview. Give yourself plenty of time to get to your destination, map out a route if you are unsure in any way. Being early gives you time to relax and prepare for your interview. If you are going to be late or unable to attend for any unforeseeable reason call ahead and let them know. This will show them that you are serious and that you take your commitments seriously.

Preparation: Get to know the company you are hoping to work for. A little background information can go a long way. You should research the company well before applying to it. You must be prepared to discuss the industry, the company's relative size within that industry and show that you know who the major players and competitors are


Frequently Asked Questions

All interview questions are designed to find out your ability to fit-in and contribute to the specific workgroup. Here are some of the most commonly asked questions to help you prepare for your interview:

Tell us about yourself?

Tell them in detail how your experience would relate to the position you are being interviewed for. Be as detailed as possible about your family background, educational background and previous job experience.

Why are you interested in this position?

Tell your employer why you chose to apply for this position. Explain why you are a perfect match for the position and how you will do full justice to the same. Use relevant examples from your family background, educational background and previous job experience.

What do you know about this company?

You should research the company well before applying to it. You must be prepared to discuss the industry, the company's relative size within that industry and show that you know who the major players and competitors are

What salary are you drawing?

The question is not difficult to answer – just be honest and give the figure. In all probability, your next employer may base your salary on this amount. However, the problem arises when you feel you are being underpaid in your current organization. You may feel tempted to lie, but do not give in, as checks can be easily made and you may be disqualified. In case you are getting additional perks, incentives or commissions, do not forget to mention them, as they are important while negotiating salary.

Things to avoid in an Interview

Things to avoid in an Interview


Poor personal appearance


Lack of interest and enthusiasm; passive and indifferent


Over-emphasis on money


Criticism of past employer


Poor eye contact with interviewer


Late to interview


Failure to express appreciation for interviewer’s time


Asks no questions about the job


Unwillingness to relocate


Indefinite answer to question


Overbearing, aggressive, conceited with ‘know-it-all’ complex


Inability to express self clearly; poor voice, poor diction, poor grammar


Lack of planning for career, no purpose or goals


Lack of confidence and poise, nervous, ill at ease


Failure to participate in activities


Expects too much too soon


Makes excuses, evasive, hedges on unfavourable factors on record


Lack of tact


Lack of courtesy, ill-mannered


Lack of vitality


Lack of maturity


Sloppy application form


No interest in company or industry


Cynical


Intolerant, strong prejudices

Tips on interview

Tips on interview helps you to get succeed in job interview by valuable Interview Tips, No matter where you studied and which school or college you studied , it doesn’t matter how much experience you have, and whom you know in Industry--if you aren't able to answers to interview questions in interview successfully, you won't get the job. Our job interview tips gives you information about how to face Interviews and covers most job interview Techniques and tips and also covers lots of things which we have to avoid during interview.

Applying for a job is an easy task however, an employer short listing a candidate’s resume and inviting for an interview is the hardest part. Employers look for several qualities in a candidate - to name a few, personal attire, knowledge and experience in the previous job, friendly and sociable person apart from other skills. Interview tips guide you on how to make use of the interview and determine whether you can be successful in the available job position and whether the company you attended for interview will give you the opportunity for professional growth and career development.

Interview is used as a platform to determine whether or not you're qualified for the job position, motivated to do the job and to find if you are the right fit for the applied position. When you attend for an interview you should answer questions in a way which is acceptable to a interviewer, but not necessarily right to the interviewer. We know many people struggle with interviews though they are the most experienced and best qualified for the job. A successful interview is critical to landing the job you want. As the job seeker ,Knowing the interview tips, interview  Dos and Don'ts  reviewing likely questions in advance and  being prepared for interview will put you in the best possible position for a successful interview.

If interviews make you nervous as they do to most people, go through our site for interview tips to know how to attend an interview and learn how to prepare and communicate in interviews. The information provided on interview tips will help a job seeker to be fully prepared before attending a job interview and to face the interview with great confidence. Interview Tips can be very handy during times when interviews get very stressful. The best way to overcome the stress is to find out what are the interview tips that a job seeker should follow prior to job interview and also to be prepared in advance by way of researching about the company as this will help during the job interview process.

Tips on interview provides valuable tips about how to face phone interviews, interview tips on topics like phone interview tips, How to Rise your Resume effectively, what dress to wear for Interview, interview etiquettes, interview management, , tips on how to conduct an interview , on campus interview tips ,Questions to ask during the interview, time management, tips on group interviews ,Tips for Negotiating for your Pay Rise, sample interview questions, salary negotiations, tips for writing resignation letters and many more  which a job seeker should bear in mind before attending a job interview. Our Interview tips provided is a Open Database where you can search or share interview questions, comment, Interview questions and answers. If you had an interview, and you would like to share the questions and answers with us then Add Questions .if you have any questions to ask, please use contact us page.

If you are visiting this website for the first time, please check Site Map section to find all job interview tips link easily. Please Bookmark our web site as we frequently add new tips on how to attend for job interviews.

Common Interview Questions and Answers

students interview, interview for students, c c++ students, Interview fear, avoid interview fear

50 Common Interview Questions and Answers :

1. Tell me about yourself:

It is the most frequently asked question in interviews. You need to have a short statement prepared in your mind.Talk about more work-related items. Describe about the things you have done and jobs you have held that relate to the position you are interviewing for. Start with the item farthest back and work up to the present.

2. Why did you leave your last job?

Stay positive in your ideas. Never refer to a major problem with management and never speak ill of supervisors, co- workers or the organization. If you do, you will be the one looking bad. Keep smiling and talk about leaving for a positive reason such as an opportunity, a chance to do something special or other forward- looking reasons.

3. What experience do you have in this field?

Speak about specifics that relate to the position you are applying for. If you do not have specific experience, get as close as you can.

4. Do you consider yourself successful?

You should always answer yes and briefly explain why. A good explanation is that you have set goals, and you have met some and are on track to achieve the others.



5. What do co-workers say about you?

Be prepared with a quote or two from co-workers. Either a specific statement or a paraphrase will work. Jill Clark, a co-worker at Smith Company, always said I was the hardest workers she had ever known. It is as powerful as Jill having said it at the interview herself.

6. What do you know about this organization?

This question is one reason to do some research on the organization before the interview. Find out where they have been and where they are going. What are the current issues and who are the major players?

7. What have you done to improve your knowledge in the last year?

Try to include improvement activities that relate to the job. A wide variety of activities can be mentioned as positive self-improvement. Have some good ones handy to mention.

8. Are you applying for other jobs?

Be honest but do not spend a lot of time in this area. Keep the focus on this job and what you can do for this organization. Anything else is a distraction.

9. Why do you want to work for this organization?

This may take some thought and certainly, should be based on the research you have done on the organization. Sincerity is extremely important here and will easily be sensed. Relate it to your long-term career goals.

10. Do you know anyone who works for us?

Be aware of the policy on relatives working for the organization. This can affect your answer even though they asked about friends not relatives. Be careful to mention a friend only if they are well thought of.

11. What kind of salary do you need?
A loaded question. A nasty little game that you will probably lose if you answer first. So, do not answer it. Instead, say something like, That's a tough question. Can you tell me the range for this position? In most cases, the interviewer, taken off guard, will tell you. If not, say that it can depend on the details of the job. Then give a wide range.

12. Are you a team player?
You are, of course, a team player. Be sure to have examples ready. Specifics that show you often perform for the good of the team rather than for yourself are good evidence of your team attitude. Do not brag, just say it in a matter-of-fact tone. This is a key point.

13. How long would you expect to work for us if hired?

Specifics here are not good. Something like this should work: I'd like it to be a long time. Or As long as we both feel I'm doing a good job.


14. Have you ever had to fire anyone? How did you feel about that?

This is serious. Do not make light of it or in any way seem like you like to fire people. At the same time, you will do it when it is the right thing to do. When it comes to the organization versus the individual who has created a harmful situation, you will protect the organization. Remember firing is not the same as layoff or reduction in force.

15. What is your philosophy towards work?

The interviewer is not looking for a long or flowery dissertation here. Do you have strong feelings that the job gets done? Yes. That's the type of answer that works best here. Short and positive, showing a benefit to the organization.

16. If you had enough money to retire right now, would you?

Answer yes if you would. But since you need to work, this is the type of work you prefer. Do not say yes if you do not mean it.

17. Have you ever been asked to leave a position?

If you have not, say no. If you have, be honest, brief and avoid saying negative things about the people or organization involved.

18. Explain how you would be an asset to this organization.

You should be anxious for this question. It gives you a chance to highlight your best points as they relate to the position being discussed. Give a little advance thought to this relationship.

19. Why should we hire you?

Point out how your assets meet what the organization needs. Do not mention any other candidates to make a comparison.

20. Tell me about a suggestion you have made.

Have a good one ready. Be sure and use a suggestion that was accepted and was then considered successful. One related to the type of work applied for is a real plus.

21. What irritates you about co-workers?

This is a trap question. Think real hard but fail to come up with anything that irritates you. A short statement that you seem to get along with folks is great.

22. What is your greatest strength?

Numerous answers are good, just stay positive. A few good examples: Your ability to prioritize, Your problem-solving skills, Your ability to work under pressure, Your ability to focus on projects, Your professional expertise, Your leadership skills, Your positive attitude

23. Tell me about your dream job.

Stay away from a specific job. You cannot win. If you say the job you are contending for is it, you strain credibility. If you say another job is it, you plant the suspicion that you will be dissatisfied with this position if hired. The best is to stay genetic and say something like: A job where I love the work, like the people, can contribute and can't wait to get to work.

24. Why do you think you would do well at this job?

Give several reasons and include skills, experience and interest.

25. What are you looking for in a job?

See answer # 23

26. What kind of person would you refuse to work with?


Do not be trivial. It would take disloyalty to the organization, violence or lawbreaking to get you to object. Minor objections will label you as a whiner.

27. What is more important to you: the money or the work?

Money is always important, but the work is the most important. There is no better answer.

28. What would your previous supervisor say your strongest point is?

There are numerous good possibilities:
Loyalty, Energy, Positive attitude, Leadership, Team player, Expertise, Initiative, Patience, Hard work, Creativity, Problem solver

29. Tell me about a problem you had with a supervisor.

Biggest trap of all. This is a test to see if you will speak ill of your boss. If you fall for it and tell about a problem with a former boss, you may well below the interview right there. Stay positive and develop a poor memory about any trouble with a supervisor.

30. What has disappointed you about a job?

Don't get trivial or negative. Safe areas are few but can include:
Not enough of a challenge. You were laid off in a reduction Company did not win a contract, which would have given you more responsibility.

31. Tell me about your ability to work under pressure.

You may say that you thrive under certain types of pressure. Give an example that relates to the type of position applied for.

32. Do your skills match this job or another job more closely?

Probably this one. Do not give fuel to the suspicion that you may want another job more than this one.

33. What motivates you to do your best on the job?

This is a personal trait that only you can say, but good examples are: Challenge, Achievement, Recognition

34. Are you willing to work overtime? Nights? Weekends?

This is up to you. Be totally honest.

35. How would you know you were successful on this job?

Several ways are good measures:
You set high standards for yourself and meet them. Your outcomes are a success.Your boss tell you that you are successful

36. Would you be willing to relocate if required?

You should be clear on this with your family prior to the interview if you think there is a chance it may come up. Do not say yes just to get the job if the real answer is no. This can create a lot of problems later on in your career. Be honest at this point and save yourself uture grief.

37. Are you willing to put the interests of the organization ahead of your own?

This is a straight loyalty and dedication question. Do not worry about the deep ethical and philosophical implications. Just say yes.

38. Describe your management style.

Try to avoid labels. Some of the more common labels, like progressive, salesman or consensus, can have several meanings or descriptions depending on which management expert you listen to. The situational style is safe, because it says you will manage according to the situation, instead of one size fits all.

39. What have you learned from mistakes on the job?

Here you have to come up with something or you strain credibility. Make it small, well intentioned mistake with a positive lesson learned. An example would be working too far ahead of colleagues on a project and thus throwing coordination off.

40. Do you have any blind spots?

Trick question. If you know about blind spots, they are no longer blind spots. Do not reveal any personal areas of concern here. Let them do their own discovery on your bad points. Do not hand it to them.

41. If you were hiring a person for this job, what would you look for?

Be careful to mention traits that are needed and that you have.

42. Do you think you are overqualified for this position?

Regardless of your qualifications, state that you are very well qualified for the position.

43. How do you propose to compensate for your lack of experience?

First, if you have experience that the interviewer does not know about, bring that up: Then, point out (if true) that you are a hard working quick learner.

44. What qualities do you look for in a boss?

Be generic and positive. Safe qualities are knowledgeable, a sense of humor, fair, loyal to subordinates and holder of high standards. All bosses think they have these traits.

45. Tell me about a time when you helped resolve a dispute between others.

Pick a specific incident. Concentrate on your problem solving technique and not the dispute you settled.

46. What position do you prefer on a team working on a project?

Be honest. If you are comfortable in different roles, point that out.

47. Describe your work ethic.

Emphasize benefits to the organization. Things like, determination to get the job done and work hard but enjoy your work are good.

48. What has been your biggest professional disappointment?

Be sure that you refer to something that was beyond your control. Show acceptance and no negative feelings.

49. Tell me about the most fun you have had on the job.

Talk about having fun by accomplishing something for the organization.

50. Do you have any questions for me?

Always have some questions prepared. Questions prepared where you will be an asset to the organization are good. How soon will I be able to be productive? and What type of projects will I be able to assist on? are examples.

Thursday, March 18, 2010

Hexaware Interview Questions

Directions for questions 1-10: Expand the following terms (HexaWare)
1. ODBC    Ans. Open Database Connectivity.
2. HTML    Ans. Hyper Text Markup Language
3. RISC    Ans. Reduced Instruction Set Computing
4. ASCII    Ans. American Standard Code For Information Interchange
5.ANSI    Ans. American National Standard Institute.
6. XML     Ans. Extended Markup Language
7. FLOPS    Ans. Floating Point Operating Per Second
8. SQL        Ans. Sequential Query Language
9. QBE    Ans. Query By Example
10. ALE    Ans. Address Latch Enable
11. What is lagging in DBMS ?     Ans. Reduced Redundancy.
Directions 12 to 20: For the following questions find the odd man out
12. Unix
      OS/2
      CMOS
      MSDOS    Ans. CMOS
13. Oracle
      Informix
      Sybase
      LISP    Ans. LISP
14. Laser
      Inkjet
      Dotmatirx
      Mouse    Ans. Mouse
15. Dir
      Cls
      Csh
      Copy    Ans. Csh
16. Bit
      Byte
      Nibble
      Digit    Ans. Digit
17. Hard Disk
      Floppy Drive
      CD ROM
      Cache    Ans. Cache
18. SQL
      QUEL
      QBE
      ORACLE    Ans. Oracle
19. C++
      JAVA
      VC++
      PASCAL    Ans. PASCAL
20. Projection Operation
      Selection Operation
      Intersection
      Set Difference Operation        Ans. Intersection
21. Which of the following is a universal gate ?
(a) OR
(b) AND
(c) XOR
(d) NOR    Ans. NOR
22. The default back end of the VB is
(a) Oracle
(b) Sybase
(c) Informics    Ans. Sybase
23. What is meant by Superconductivity?    Ans. No reistance
24. Viscosity                    Ans. Friction
25. What is the Lock Based Protocol used for?    Ans. Concurrency Control in DBMS
Directions for question 25 to 32: Convert the decimal numbers on the left to the required form
25. 9's complement of 28    Ans. 71
26. Binary of 58        Ans. 111010
27. Octal of 359        Ans.547
28. Hexadecimal of 650    Ans.28A
29. BCD of 18            Ans.0001 1000
30. BCD of 34.8        Ans.0011 0100.1000
31. Excess-3 code of 6    Ans.1001
32. Excess-3 code of 9    Ans.1100
33.  If Ax + By = 1F16; Cx + Dy = 2510 .Find the value of x and y
34. Semaphore is used for
(a) synchronization
(b) dead-lock avoidence
(c) box
(d) none                        Ans.  A
35. For addressing 1 MB memory, the  number of address lines required,
(a)11
(b)16
(c)22
(d) 24                            Ans.  b
36. Which of the following remains in memory temporarily
(a) Resident portion of COMMAND.COM
(b) Transient portion of COMMAND.COM
(c) API
(d) Disk BIOS                        Ans.  b
37. Pick the odd man out
(a) IO.SYS
(b) MSDOS.SYS
(c) ROM-BIOS
(d) COMMAND.COM                Ans.  C
38. OS/2 is a
(a) Single User OS
(b) Multi User OS
(c) Multi Tasking OS
(d) None of these                    Ans.  C
39. Bootstrap loader program is a program belonging to
(a) ROM startup software
(b) ROM extension software
(c) ROM BIOS software
(d) ROM Basic software                Ans.  A
40. The entry of starting cluster of a file is present in
(a) Boot Parameters
(b) Directory
(c) FAT
(d) Partition Table and master boot program        Ans.  C

JAVA Servlet Interview Questions

        Interview Based Questions

1. What are the types of ServletEngines?
Standalone ServletEngine:A standalone engine is a server that includes built-in support for servlets.

Add-on ServletEngine:Its a plug-in to an existing server.It adds servlet support to a server that was not originally designed with servlets in mind.

Embedded ServletEngine:

2.What is the difference between a Generic Servlet and Http Servlet?

Generic Servlet                    Http Servlet
Class which internally implements     An abstract class which acts as a child class both for Servlet and ServletConfig     GenericServlet and in addition provides interfaces. some additional methods
like doGet(),doPost(),doDelete() &
doPut().

3.What is a Session Id?

It is a unique id assigned by the server to the user when a user first accesses a site or an application ie. when a request is made.

4. List out Differences between CGI Perl and Servlet?

Servlet                            CGI

Platform independent                Platform dependent.
Language dependent                Language independent.

5. What is Bootstrapping in RMI?

Dynamic loading of stubs and skeletons is known as Boot Strapping.

6. What are different types of Exceptions?.
Runtime exceptions, Errors, Program Exceptions

7. What are types of applets?.
Trusted Applets: Applets with predefined security
Untrusted Applets: Applets without any security

8. When does an Exception occur?.

Whenever an error occurs in an Application,(either at compile time)or runtime,it raises an Exception.

9. What is servlet tunnelling?.
Used in applet to servlet communications, a layer over http is built so as to enable object serialization.

10. What is a cookie?.

Cookies are a way for a server to send some information to a client to store and for the server to later retrieve its data from that client.Web browser supports 20 cookies/host of 4kb each.

11.What is the frontend in Java?.Also what is Backend?.
Frontend: Applet
Backend : Oracle, Ms-Access(Using JDBC).

12. Define a JSP?.
Java Server Pages includes scripplets of Servletcode in an Html page.This creates dynamism in the other-wise static HTML.A JSP is a document that describes how to process a request to creeate response.

13. The length of an identifier is

14. Stored procedures can be called by Callable Statement.

15. Stack class implements LIFO(Last In First Out).

16. Servlet Class defines init.

17. Reference of any instance variable inside a static method is legal if declared static.

18. What will a read() function do?.
A method in Input Stream.It reads a single byte or an array of bytes.Returns no of bytes read or -1 if EOF(End of file)is reached.

19.To implement a Throwable array,which class is used.
Vector
LinkedList
Stack
ArrayList - Answer(To be Confirmed)

20. The method for precompiled SQL Statement in JDBC is prepareStatement().

21. Static binding occurs at
Compile Time
Runtime
Both at compile and runtime.

22. Virtual Methods are default in
Java
C
C++ - Answer
All

23. Storage space in java is of the form
Stack
Queue
Heap
List

24. What is java code embedded in a web page known as
Applets
Servlets
scriptlets
snippets

25. Which of the following attributes are compulsory with an <applet> tag?.
code,height & width.

26. What does 'CODEBASE' in an applet tag specify?.
Files absolute path.

27. What are AccessSpecifiers & Access Modifiers.
Access Specifiers: Give access previleges to outside applications or users. They are :-
Public: any one can access
private:only class members can access.cannot be inherited.
protected: can be accessed by a derived class.
default: can access data from the current directory.

Access Modifiers: Which gives additional meaning to data, methods and classes.
(i) Final: cannot be modified at any point of time.

28. Tools provided by JDK
(i)    javac - compiler
(ii)    java - interpretor
(iii)    jdb - debugger
(iv)    javap - Disassembles
(v)    appletviewer - Applets
(vi)    javadoc - documentation generator
(vii)    javah - 'C' header file generator

29.Hostile Applets:Its an applet which when downloaded attempts to exploit your system's resources in an inappropriate manner.It performs or causes you to perform an action which you would not otherwise care to perform.

30.RemoteObjects: Objects that have methods that can be called accross virtual machines are 0000000000000000Remote Objects.An object becomes Remote by implementing Remote Interface.

31.Compiling: Conversion of Programmer-readable Text into Bytecodes,which are platform independent,is known as Compiling.

32.Java Primitive Data Types:
Byte-8-bit
short-16-bit
int-32-bit
Long-64-bit
Float-32-bit floating point
Double-64-bit floating point
Char-16-bit Unicode

33.What is a unicode?
Unicode is a standard that supports International Characters.

34. What are blocks?.
They are statements appearing within braces {}.

35. What are types of Java applications?.

(i) Standalone applications(No browser).
(ii) Applets(Browser).

36. What is the method that gets invoked first in a stand alone application?.

The main()method.

37. What is throwing an Exception?.
The act of passing an Exception Object to the runtime system is called Throwing an Exception.

38. What are the packages in JDK?.

There are 8 packages
(i) java.lang(ii)java.util(iii)java.io(iv)java.applet(v) java.awt
(vi) java.awt.image(vii)java.awt.peer(viii)java.awt.net

39. What is a thread?.
Its a single sequential stream of execution.

40. What is runnable?.
Its an Interface through which Java implements Threads.The class can extend from any class but if it implements Runnable,Threads can be used in that particular application.

41. What is preemptive and Non-preemptive Time Scheduling?.
 Preemptive: Running tasks are given small portions of time to execute by using time-slicing.
Non-Preemptive: One task doesn't give another task a chance to run until its finished or has normally yielded its time.

42. What is synchronization?.
Two or more threads trying to access the same method at the same point of time leads to synchronization.If that particular method is declared as synchronized only one thread can access it at a time. Another thread can access it only if the first thread's task is complete.

43. What are the various thread priorities?.

(i)  Min-Priority-value(1).
(ii) Normal-Priority-value(5).
(iii)Max-Priority-value(10).

44.What is Inter-Thread communication?.
To exchange information between two threads.

45.The package java.applet.* has only one class.

46.BorderLayout is the default layout of Dialog object.

47.executeQuery() returns ResultSet.

48.Throwable class is a sub-class of object and implements Serializable.

49.Super class of TextArea and TextField is TextComponent.

50. Skeletons are server side proxies and stubs are client side proxies.

51. GridBagConstraints class helps in positioning of parameters of a
component within an object laidout using GridBagLayout.

52. Netscape introduced JScript language - True

53. EventDelegation model was introduced by JDK 1.1 - False

54. StringTokenizer provides two constructors - False

55. java.applet is one of the smallest package in Java API - True

56. Drag and Drop API consist of java.awt.dnd package - False

57. What is IP?.
IP is Internet Protocol. It is the network protocol which is used to send information from one computer to another over the network over the internet in the form of packets.

58. What is a port?.
A port is an 16-bit address within a computer.Ports for some common Internet Application protocols.

File Transfer Protocol-21.
Telnet Protocol-23.
Simple Mail Transfer Protocol-25.
Hypertext Transfer Protocol-80.

59.What is hypertext?.
Sockets are endpoints of Internet Communication.They are associated with a host address and a port address.
Clients create client sockets and connect them to server sockets.UDP is a connectionless protocol.

MIME(Multipurpose Internet Mail Extension) is a general method by which the content of different types of Internet objects can be identified.

61. What is an abstract class?.
A class which cannot be Instantiated.

62.ServletRunner options are:
-p-port number(8080).
-b-backlog connections(50).
-m-maximum no.of connection handlers(100).
-t-connection timeout in milliseconds
-d-servlet directory (current directory)
-s-servlet properties file

63.How many standard ports are available?.
1024.

64.What is a policy?.
It's an abstract class for representing the system security policy for a Java application environment(specifying which permissions are available for code from various sources). Java security properties file resides in <JAVA-HOME>/lib/security/java.security directory. Value of "policy.provider" should be changed.

65. What are different ways of Session-Tracking?.
(i) User-Authorization
(ii) Hidden Files
(iii) Persistant Cookies
(iv) URL Rewriting.

66. If the browser does not support cookies or if they are disabled, how is session tracking done?.

Session tracking is done by URL Rewriting.
* Multiple requests can be handled by a servlet and it also can synchronize them.ex: On-line conferencing.
* Servlets have no Graphic User Interface.
* We can synchronize the service() method for a major performance impact as multiple requests are involved in case of servlets.
* We can make a servlet handle a single client/request by implementing single threadmodel interface.

67. What is a Swing?.
It is a GUI component with a pluggable look and feel.

68. What is default Look-and-Feel of a Swing Component?.
Java Look-and-Feel.

69. Awt Components and Swing Components can be inter-mingled in an Application - False

70. What are the features coming with JFC?.
(i) Pluggable Look-and-Feel
(ii) Accessibility API
(iii) Java 2D/API(JDK 1.2).
(iv) Drag and Drop Support(JDK 1.2)

71. What does x mean in javax.swing?.       
Extension of java.
72. Images can be displayed on Swing Components
- True
73. Borders can be changed or added for a LightWeight Components
- True
74. Swing Components are always rectangular
- False
75. When Swing components overlap with Heavyweight components, it is the latter that is on the top
 - True

76. What are the components which are termed to be Heavy-weight, available in Light-weight component?.

77. What are invisible components?.
They are light weight components that perform no painting, but can take space in the GUI.

78. What is the default layout for a ContentPane in JFC?.
BorderLayout.

79. What are the borders provided by Swing?.
(i) Simple        (ii) Matte        iii) Titled    iv) Compound.

80. What does Realized mean?.
Realized mean that the component has been painted on screen or that is ready to be painted. Realization can take place by invoking any of these methods.
setVisible(true), show() or pack().

81. What is a convertor?.
Its an application that converts distance measurements between metric and U.S units.

82. What is the return type of interrupt method?.        void.
83. What is the superclass of exception?.        Throwable.
84. What is servlet exception?.            It indicates that there is a problem in the servlet.
85. What is the difference between a Canvas and a Scroll Pane?.
=====================================================================
Canvas                    ScrollPane
=====================================================================
Its a component                             Its a container.
------------------------------------------------------------------------------------------------------------------------------
A rectangular area where the application        Implements horizontal and vertical
can draw or trap input events.            scrolling.
=====================================================================
86. What are the restrictions imposed by a Security Manager on Applets?.

i) cannot read or write files on the host that's executing it.
ii) cannot load libraries or define native methods.
iii) cannot make network connections except to the host that it came from
iv) cannot start any program on the host that's executing it.
v) cannot read certain system properties.
vi) windows that an applet brings up look different than windows that an application brings up.

87. Can we access a database using applets?.            Yes.
88. What is the default HttpRequest method?.            doGet().
89. What is the life cycle of a servlet?.
Removing Handling zero or more client requests.Loading and Initializing.
90. RPC stands for Remote Procedure Call.
91. The three layers in RMI are Application Layer,RemoteReferenceLayer and Network Layer.

Interviewer's Questions type

Type of Questions

Interviewers use five different types of questions - directive, non-directive, hypothetical, behavior descriptive, and stress. Being aware of the different types can help you in the preparation stage as you  build your skills  inventory. It may also help you focus in on exactly what is being asked and what the employer is looking for in specific questions.

 

 Directive Questions

 

The interviewer determines the focus of your answer. The information that the interviewer wants is very clear. If you have completed the research on yourself, this type of question should be easy to answer.

 

 Example: "What skills do you have that relate to this position?"

 

"I have very good communication and interpersonal skills that I have refined through several summer and part-time jobs working with the public. In addition, I am fluent in both English and French."

 

 Non-Directive Questions

 

You determine the focus of your answer. The interviewer asks a general question and does not ask for specific information. The most common non-directive question is

 

"Tell me about yourself."

 

When answering the question, keep in mind that the employer is interested in knowing how your background and personality qualify you for the job. In your answer, you should cover four areas: your education, related experience, skills and abilities, and personal attributes. As you talk about these areas, relate them to the job you are seeking. Decide what your response will be before starting to speak, this helps to keep responses concise.

 

Example: " Tell me about yourself."

 

"I have a Bachelor of Arts Degree in Psychology, and have recently completed the course

 

in Volunteer Management through the Volunteer Center of Winnipeg. These have given me a strong background in many of the principles of human behavior and the recruitment, training, and supervision of volunteers. I have experience in working with young adults in a helping capacity, both through my position as a Peer Advisor at the University of Manitoba, and as a camp counselor at a camp for behaviorally troubled adolescents. Both of these positions involved individual counseling, facilitating discussion groups, and teaching young people about health issues - all of which relate directly to the services which I would be training volunteers to provide within your organization. In addition, I thoroughly enjoy working with young people, and can establish rapport with them easily."

 

 Hypothetical or Scenario Questions

 

When asking a hypothetical question, the interviewer describes a situation, which you may encounter in the position and asks how you would react in a similar situation. This is a good way to test problem-solving abilities. When answering this type of question, try applying a simple problem solving model to it – gather information, evaluate the information, priories the information, seek advice, weigh the alternatives, make a decision, communicate the decision, monitor the results and modify if necessary.

 

Example: "Suppose you are working your first day in our laboratory, and a fire at a nearby work station breaks out. What would you do?"

 

"Before I start working in any laboratory, I always locate the emergency equipment, such as eye washes, fire blankets and alarms. I would also review the safety protocols. So in this situation, I would be aware of these. As soon as I noticed the fire, I would shut down my experiment and if the fire is significant, I would pull the firm alarm and help to evacuate the lab. In the case of very small flame, I would ask the staff member at the station what I could do to help, Which would vary with the type of substances involved.”

 

 Behavior Descriptive or Behavioral Questions

 

This type of question is becoming increasingly popular in interview situations. It asks what you did in a particular situation rather than what you would do. Situations chosen usually follow the job description fairly closely. Some employers feel that examples of past performance will help them to predict future performance in similar situations. There is no right or wrong answer to this type of question, but keep in mind that you should relate the answer to the position. If you are interviewing for a research position, talk about a research project you completed.

 

Example: "Give me an example of a work situation in which you were proud of your performance."

 

"While working as a sales representative for XYZ Company for the summer, I called on Prospective clients and persuaded them of the ecological and economic benefits of Recycling. I also followed up on clients to ensure that they were satisfied with the service They received. This involved both telephone and in-person contacts. I increased sales 34% over the same period in the previous year."

 

When preparing for this type of questioning, it is crucial that you review the skills and qualities that the position would require and identify specific examples from your past which demonstrated those traits.

 

Stress Questions

 

Some questions will surprise you and possibly make you feel uncomfortable during an interview. For

 

Example:"  Which do you prefer, fruits or vegetables?" There are many reasons why an interviewer might ask such questions. They may want to see how you react in difficult situations, or they may simply be trying to test your sense of humor. Such questions may directly challenge an opinion that you have just stated or say something negative about you or a reference. Sometimes they ask seemingly irrelevant questions such as,

 

"If you were an animal, what type of animal would you be?"

 

The best way to deal with this type of question is to recognize what is happening. The interviewer is trying to elicit a reaction from you. Stay calm, and do not become defensive. If humor comes naturally to you, you might try using it in your response, but it is important to respond to the question. What you say is not nearly as important as maintaining your composure.

 

Example: "Which do you like better, Lions or Tigers?"

 

"Oh, lions definitely. They appear so majestic and are very sociable. To be honest, I think that seeing The Lion King four times has probably contributed to this!"

Java , applet , swing Interview quesions with answers

1]Which declaration of the main method below would allow a class to be started as a standalone program. Select the one correct answer.
a)    public static int main(char args[])
b)    public static void main(String args[])
c)    public static void MAIN(String args[])
d)    public static void main(String args)
e)    public static void main(char args[])
What all gets printed when the following code is compiled and run? Select the three correct answers.
public class xyz {
   public static void main(String args[]) {
      for(int i = 0; i < 2; i++) {
         for(int j = 2; j>= 0; j--) {
            if(i == j) break;
            System.out.println("i=" + i + " j="+j);
         }      }   } }
a)    i=0 j=0
b)    i=0 j=1
c)    i=0 j=2
d)    i=1 j=0
e)    i=1 j=1
f)    i=1 j=2
g)    i=2 j=0
h)    i=2 j=1
i)    i=2 j=2
What gets printed when the following code is compiled and run with the following command -
java test 2      Select the one correct answer.
public class test {
   public static void main(String args[]) {
      Integer intObj=Integer.valueOf(args[args.length-1]);
      int i = intObj.intValue();
      if(args.length > 1)
         System.out.println(i);
      if(args.length > 0)
         System.out.println(i - 1);
      else
         System.out.println(i - 2);
   }}
a)    test
b)    test -1
c)    0
d)    1
e)    2
In Java technology what expression can be used to represent number of elements in an array named arr ?
How would the number 5 be represented in hex using up-to four characters.
Which of the following is a Java keyword. Select the four correct answers.
a)    extern
b)    synchronized
c)    volatile
d)    friend
e)    friendly
f)    transient
g)    this
h)    then
Is the following statement true or false. The constructor of a class must not have a return type.
a)    true             b)false
What is the number of bytes used by Java primitive long. Select the one correct answer.
a)    The number of bytes is compiler dependent.
b)    2
c)    4
d)    8
e)    64
What is returned when the method substring(2, 4) is invoked on the string "example"? Include the answer in quotes as the result is of type String.

Which of the following is correct? Select the two correct answers.
a)    The native keyword indicates that the method is implemented in another language like C/C++.
b)    The only statements that can appear before an import statement in a Java file are comments.
c)    The method definitions inside interfaces are public and abstract. They cannot be private or protected.
d)    A class constructor may have public or protected keyword before them, nothing else.

What is the result of evaluating the expression 14 ^ 23. Select the one correct answer.
a)    25        37     6     31     17     9     24

11] Which of the following are true. Select the one correct answers.
a)    && operator is used for short-circuited logical AND.
b)    ~ operator is the bit-wise XOR operator.
c)    | operator is used to perform bitwise OR and also short-circuited logical OR.
d)    The unsigned right shift operator in Java is >>.

Name the access modifier which when used with a method, makes it available to all the classes in the same package and to all the subclasses of the class.

Which of the following is true. Select the two correct answers.
a)    A class that is abstract may not be instantiated.
b)    The final keyword indicates that the body of a method is to be found elsewhere. The code is written in non-Java language, typically in C/C++.
c)    A static variable indicates there is only one copy of that variable.
d)    A method defined as private indicates that it is accessible to all other classes in the same package.

14] What all gets printed when the following program is compiled and run. Select the two correct answers.
public class test {
   public static void main(String args[]) {
      int i, j=1;
      i = (j>1)?2:1;
      switch(i) {
        case 0: System.out.println(0); break;
        case 1: System.out.println(1);
        case 2: System.out.println(2); break;
        case 3: System.out.println(3); break;
      }       }    }
a)    0     1     2     3

15] What all gets printed when the following program is compiled and run. Select the one correct answer.
public class test {
   public static void main(String args[]) {
      int i=0, j=2;
      do {
         i=++i;
         j--;
      } while(j>0);
      System.out.println(i);
   }}
   a) 0         1     2    The program does not compile because of statement "i=++i;"
 
16]What all gets printed when the following gets compiled and run. Select the three correct answers.
public class test {
    public static void main(String args[]) {
        int i=1, j=1;
        try {
            i++;
            j--;
            if(i/j > 1)
                i++;
        }
        catch(ArithmeticException e) {
            System.out.println(0);
        }
        catch(ArrayIndexOutOfBoundsException e) {
            System.out.println(1);
        }
        catch(Exception e) {
            System.out.println(2);
        }
        finally {
            System.out.println(3);
        }
        System.out.println(4);
     }    }
 
a)    0     1     2     3     4
 17] What all gets printed when the following gets compiled and run. Select the two correct answers.
public class test {
    public static void main(String args[]) {
        int i=1, j=1;
        try {
            i++;
            j--;
            if(i == j)
                i++;
        }
        catch(ArithmeticException e) {
            System.out.println(0);
        }
        catch(ArrayIndexOutOfBoundsException e) {
            System.out.println(1);
        }
        catch(Exception e) {
            System.out.println(2);
        }
        finally {
            System.out.println(3);
        }
        System.out.println(4);
     }    }
a)    0     1     2     3     4
What all gets printed when the following gets compiled and run. Select the two correct answers.

public class test {
    public static void main(String args[]) {
    String s1 = "abc";
    String s2 = "abc";
    if(s1 == s2)
        System.out.println(1);
    else
        System.out.println(2);
    if(s1.equals(s2))
        System.out.println(3);
    else
        System.out.println(4);
    }    }

a)    1
b)    2
c)    3
d)    4
19]What all gets printed when the following gets compiled and run. Select the two correct answers.
public class test {
    public static void main(String args[]) {
    String s1 = "abc";
    String s2 = new String("abc");
    if(s1 == s2)
        System.out.println(1);
    else
        System.out.println(2);
    if(s1.equals(s2))
        System.out.println(3);
    else
        System.out.println(4);
    }  }      
a)    1
b)    2
c)    3
d)    4

20] Which of the following are legal array declarations. Select the three correct answers.
int i[5][];
int i[][];
int []i[];
int i[5][5];
int[][] a;

21]What is the range of values that can be specified for an int. Select the one correct answer.
a)    The range of values is compiler dependent.
b)    -231 to 231 - 1
c)    -231-1 to 231
d)    -215 to 215 - 1
e)    -215-1 to 215

How can you ensure that the memory allocated by an object is freed. Select the one correct answer.
a)    By invoking the free method on the object.
b)    By calling system.gc() method.
c)    By setting all references to the object to new values (say null).
d)    Garbage collection cannot be forced. The programmer cannot force the JVM to free the memory used by an object.

23]What gets printed when the following code is compiled and run. Select the one correct answer.
public class test {
    public static void main(String args[]) {
    int i = 1;
    do {
        i--;
    } while (i > 2);
    System.out.println(i);
    }
 }
a)    0
b)    1
c)    2
d)    -1

24]Which of these is a legal definition of a method named m assuming it throws IOException, and returns void. Also assume that the method does not take any arguments. Select the one correct answer.
a)    void m() throws IOException{}
b)    void m() throw IOException{}
c)    void m(void) throws IOException{}
d)    m() throws IOException{}
e)    void m() {} throws IOException

25] Which of the following are legal identifier names in Java. Select the two correct answers.
a)    %abcd
b)    $abcd
c)    1abcd
d)    package
e)    _a_long_name

At what stage in the following method does the object initially referenced by s becomes available for garbage collection. Select the one correct answer.
void method X()  {
    String r = new String("abc");
    String s = new String("abc");
    r = r+1; //1
    r = null; //2
    s = s + r; //3
} //4
a)    Before statement labeled 1
b)    Before statement labeled 2
c)    Before statement labeled 3
d)    Before statement labeled 4
e)    Never.

27]String s = new String("xyz"); Assuming the above declaration, which of the following statements would compile. Select the one correct answer.
a)    s = 2 * s;
b)    int i = s[0];
c)    s = s + s;
d)    s = s >> 2;
e)    None of the above.

28]Which of the following statements related to Garbage Collection are correct. Select the two correct
a)    It is possible for a program to free memory at a given time.
b)    Garbage Collection feature of Java ensures that the program never runs out of memory.
c)    It is possible for a program to make an object available for Garbage Collection.
d)    The finalize method of an object is invoked before garbage collection is performed on the object.

29]If a base class has a method defined as --void method() { }
Which of the following are legal prototypes in a derived class of this class. Select the two correct answers.
a)    void method() { }
b)    int method() { return 0;}
c)    void method(int i) { }
d)    private void method() { }

30] In which all cases does an exception gets generated. Select the two correct answers.
a)    int i = 0, j = 1;
b)    if((i == 0) || (j/i == 1))
c)    if((i == 0) | (j/i == 1))
d)    if((i != 0) && (j/i == 1))
e)    if((i != 0) & (j/i == 1))

31] Which of the following statements are true. Select the two correct answers.
a)    The wait method defined in the Thread class, can be used to convert a thread from Running state to Waiting state.
b)    The wait(), notify(), and notifyAll() methods must be executed in synchronized code.
c)    The notify() and notifyAll() methods can be used to signal and move waiting threads to ready-to-run state.
d)    The Thread class is an abstract class.

Which keyword when applied on a method indicates that only one thread should execute the method at a time. Select the one correct answer.
a)    transient
b)    volatile
c)    synchronized
d)    native
e)    static
f)    final

What is the name of the Collection interface used to represent elements in a sequence (in a particular order). Select the one correct answer.
a)    Collection
b)    Set
c)    List
d)    Map

34]Which of these classes implement the Collection interface SortedMap. Select the one correct answers.
a)    HashMap
b)    Hashtable
c)    TreeMap
d)    HashSet
e)    TreeSet
f)    Vector

35]Which of the following are true about interfaces. Select the two correct answers.
a)    Methods declared in interfaces are implicitly private.
b)    Variables declared in interfaces are implicitly public, static, and final.
c)    An interface can extend any number of interfaces.
d)    The keyword implements indicate that an interface inherits from another.

Assume that class A extends class B, which extends class C. Also all the three classes implement the method test(). How can a method in a class A invoke the test() method defined in class C (without creating a new instance of class C). Select the one correct answer.
a)    test();
b)    super.test();
c)    super.super.test();
d)    ::test();
e)    C.test();
f)    It is not possible to invoke test() method defined in C from a method in A.

37]What is the return type of method round(double d) defined in Math class.

38]What gets written on the screen when the following program is compiled and run. Select one right ans
public class test {
   public static void main(String args[]) {
   int i;
   float  f = 2.3f;
   double d = 2.7;
   i = ((int)Math.ceil(f)) * ((int)Math.round(d));
   System.out.println(i);
   } }
a)    4
b)    5
c)    6
d)    6.1
e)    9
39]Is the following statement true or false. As the toString method is defined in the Object class, System.out.println can be used to print any object.
a)    true      false
40] Which of these classes defined in java.io and used for file-handling are abstract. Select two correct ans a)    InputStream
b)    PrintStream
c)    Reader
d)    FileInputStream
e)    FileWriter
41]Name the collection interface used to represent collections that maintain unique elements.
42]What is the result of compiling and running the following program.

public class test {
   public static void main(String args[]) {
      String str1="abc";
      String str2="def";
      String str3=str1.concat(str2);

      str1.concat(str2);
      System.out.println(str1);
   }
}


a)    abc
b)    def
c)    abcabc
d)    abcdef
e)    defabc
f)    abcdefdef

43]Select the one correct answer. The number of characters in an object of a class String is given by
a)    The member variable called size
b)    The member variable called length
c)    The method size() returns the number of characters.
d)    The method length() returns the number of characters.

Select the one correct answer. Which method defined in Integer class can be used to convert an Integer object to primitive int type.
a)    valueOf
b)    intValue
c)    getInt
d)    getInteger

45]Name the return type of method hashCode() defined in Object class, which is used to get the unique hash value of an Object.

46]Which of the following are correct. Select the one correct answer.
a)    An import statement, if defined, must always be the first non-comment statement of the file.
b)    private members are accessible to all classes in the same package.
c)    An abstract class can be declared as final.
d)    Local variables cannot be declared as static.

Name the keyword that makes a variable belong to a class, rather than being defined for each instance of the class. Select the one correct answer.
a)    static
b)    final
c)    abstract
d)    native
e)    volatile
f)    transient

48]Which of these are core interfaces in the collection framework. Select the one correct answer.
a)    Tree
b)    Stack
c)    Queue
d)    Array
e)    LinkedList
f)    Map
 
Which of these statements are true. Select the two correct answers.
a)    For each try block there must be at least one catch block defined.
b)    A try block may be followed by any number of finally blocks.
c)    A try block must be followed by at least one finally or catch block.
d)    If both catch and finally blocks are defined, catch block must precede the finally block.

==================================================================================================
The remaining questions are related to AWT, event classes, and layout managers. These topics are not included in 1.4 version of the exam.


The default layout manager for a Frame is ...
a)    FlowLayout
b)    BorderLayout
c)    GridLayout
d)    GridBagLayout
e)    CardLayout

51]Which of the following are valid adapter classes in Java. Select the two correct answers.
a)    ComponentAdapter
b)    ActionAdapter
c)    AdjustmentAdapter
d)    ItemAdapter
e)    FocusAdapter

52]Which method defined in the EventObject class returns the Object that generated an event. The method should be given in the format - return_type method_name();

Which of the following object receives ActionEvent. Select the four correct answers.
a)    List
b)    Button
c)    Choice
d)    CheckBox
e)    TextField
f)    MenuItem

54]Name the class that may be used to create submenus in pull-down menus.

55]In which class is the wait() method defined. Select the one correct answer.
a)    Applet
b)    Runnable
c)    Thread
d)    Object

Which is the only layout manager that always honors the size of a component. Select the one correct answer.
a)    FlowLayout
b)    GridLayout
c)    BorderLayout
d)    CardLayout
e)    GridBagLayout

Which of these are valid Event Listener interfaces. Select the two correct answers.
a)    MouseMotionListener
b)    WindowListener
c)    DialogListener
d)    PaintListener

58]Which abstract class is the super class of all menu-related classes.

Answers to Sample Test 1

1)    b
2)    b, c, f
3)    d. Note that the program gets one command line argument - 2. args.length will get set to 1. So the condition if(args.length > 1) will fail, and the second check if(args.length > 0) will return true.
4)    arr.length
5)    4]Any of these is correct - 0x5, 0x05, 0X05, 0X5
6)    b, c, f, g
7)    a
8)    d
9)    "am"
10)    a, c. Please note that b is not correct. A package statement may appear before an import statement. A class constructor may be declared private also. Hence d is incorrect.
11)    a
12)    a
13)    12]protected
14)    a, c
15)    b, c
16)    c
17)    a, d, e
18)    d, e
19)    18]a, c
20)    b, c
21)    20]b, c, e
22)    b
23)    d
24)    23]a
25)    a
26)    b, e . The option c is incorrect because a Java identifier name cannot begin with a digit.
27)    26]d
28)    c
29)    c, d
30)    a, c
31)    30]b, d
32)    b, c
33)    c
34)    c
35)    c
36)    35]b, c
37)    f
38)    long
39)    e
40)    a
41)    a, c
42)    41]Set
43)    a
44)    d
45)    b
46)    45]int
47)    d
48)    a
49)    f
50)    c, d
51)    50]b
52)    a, e
53)    Object getSource();
54)    a, b, e, f
55)    Menu
56)    d
57)    a
58)    a, b
59)    MenuComponent

Mock Exam 2
Which of the following are Java keywords? Select the three correct answers.
a)    external
b)    implement
c)    throw
d)    void
e)    integer
f)    private
g)    synchronize
h)    unsigned


Which of the following are legal definitions of the main method that can be used to execute a class. Select the one correct answer.
a)    public void main(String args)
b)    public static int main(String args[])
c)    public static void main(String args[])
d)    static public void MAIN(String args[])
e)    public static void main(string args[])
f)    public static void main(String *args)


Which of these are legal array declarations or definitions? Select the two correct answers.
a)    int[] []x[];
b)    int *x;
c)    int x[5];
d)    int[] x = {1,2,3};


Name the collection interface used to represent a sequence of numbers in a fixed order.


The class Hashtable is used to implement which collection interface. Select the one correct answer.
a)    Table
b)    List
c)    Set
d)    SortedSet
e)    Map


What gets printed when the following program is compiled and run? Select the one correct answer.


class test {
    public static void main(String args[]) {
        int i;
        do {
            i++;
        }
        while(i < 0);
        System.out.println(i);
    }
}


a)    The program does not compile as i is not initialized.
b)    The program compiles but does not run.
c)    The program compiles and runs but does not print anything.
d)    The program prints 0.
e)    The program prints 1.


What gets printed when the following program is compiled and run? Select the one correct answer.

class xyz {
    static int i;
    public static void main(String args[]) {

        while (i < 0) {
            i--;
        }
        System.out.println(i);
    }
}


a)    The program does not compile as i is not initialized.
b)    The program compiles but does not run.
c)    The program compiles and runs but does not print anything.
d)    The program prints 0.
e)    The program prints 1.


What gets printed when the following program is compiled and run? Select the one correct answer.

class xyz {
 
    public static void main(String args[]) {
        int i,j,k;
        for (i = 0; i < 3; i++) {
            for(j=1; j < 4; j++) {
                for(k=2; k<5; k++) {
                    if((i == j)   && (j==k))
                        System.out.println(i);
                }               
            }
        }
    }
}


a)    0
b)    1
c)    2
d)    3
e)    4


Using up to four characters what is the Java representation of the number 23 in hex?


What gets printed when the following program is compiled and run? Select the one correct answer.

class test {
    static boolean check;
    public static void main(String args[]) {
        int i;
        if(check == true)
            i=1;
        else
            i=2;

        if(i=2) i=i+2;
        else i = i + 4;
        System.out.println(i);
     }
}


a)    3
b)    4
c)    5
d)    6
e)    The program does not compile because of the statement if(i=2)


Select the one correct answer. The smallest number that can be represented using short primitive type in Java is -
a)    0
b)    -127
c)    -128
d)    -16384
e)    -32768
f)    The smallest number is compiler dependent.


Given the following declarations, which of the assignments given in the options below would compile. Select the two correct answers.

a)    int i = 5;
b)    boolean t = true;
c)    float f = 2.3F;
d)    double d = 2.3;


e)    t = (boolean) i;
f)    f = d;
g)    d = i;
h)    i = 5;
i)    f = 2.8;


What gets printed when the following program is compiled and run. Select the one correct answer.

public class incr {
    public static void main(String args[]) {
        int i , j;
        i = j = 3;
        int n = 2 * ++i;
        int m = 2 * j++;
        System.out.println(i + " " + j + " " + n + " " + m);
    }
}


a)    4 4 8 6
b)    4 4 8 8
c)    4 4 6 6
d)    4 3 8 6
e)    4 3 8 8
f)    4 4 6 8


Given two non-negative integers a and b and a String str, what is the number of characters in the expression str.substring(a,b) . Select the one correct answer.
a)    a + b
b)    a - b
c)    b - a - 1
d)    b - a + 1
e)    b - a
f)    b


What is the result of compiling and running the following program. Select the one correct answer.

class test {
    public static void main(String args[]) {
        char ch;
        String test2 = "abcd";
        String test = new String("abcd");
        if(test.equals(test2)) {
            if(test == test2)
                ch = test.charAt(0);
            else
                ch = test.charAt(1);              
        }
        else {
            if(test == test2)
                ch = test.charAt(2);
            else               
                ch = test.charAt(3);
        }
        System.out.println(ch);
    }
}


a)    'a'
b)    'b'
c)    'c'
d)    'd'


What is the result of compiling and running the following program. Select the one correct answer.

class test {
    public static void main(String args[]) {
     int i,j=0;
     for(i=10;i<0;i--) { j++; }
     switch(j) {
     case (0) :
         j=j+1;
     case(1):
         j=j+2;
         break;
     case (2) :
         j=j+3;
         break;
    
     case (10) :
         j=j+10;
         break;
     default :
         break;
     }
   System.out.println(j);
   }
}


a)    0
b)    1
c)    2
d)    3
e)    10
f)    20


What is the number displayed when the following program is compiled and run.

class test {
    public static void main(String args[]) {
        test test1 = new test();
            System.out.println(test1.xyz(100));   
    }
    public int xyz(int num) {
        if(num == 1) return 1;
        else return(xyz(num-1) + num);
    }
}




Which of the following statements are true. Select the one correct answer.
a)    Arrays in Java are essentially objects.
b)    It is not possible to assign one array to another. Individual elements of array can however be assigned.
c)    Array elements are indexed from 1 to size of array.
d)    If a method tries to access an array element beyond its range, a compile warning is generated.


Which expression can be used to access the last element of an array. Select the one correct answer.
a)    array[array.length()]
b)    array[array.length() - 1]
c)    array[array.length]
d)    array[array.length - 1]


What is the result of compiling and running the following program. Select the one correct answer.

class test {
    public static void main(String args[]) {
        int[] arr = {1,2,3,4};
        call_array(arr[0], arr);
        System.out.println(arr[0] + "," + arr[1]);       
    }
    static void call_array(int i, int arr[]) {
        arr[i] = 6;
        i = 5;
    }   
}


a)    1,2
b)    5,2
c)    1,6
d)    5,6


Which of the following statements are correct. Select the one correct answer.
a)    Each Java file must have exactly one package statement to specify where the class is stored.
b)    If a Java file has both import and package statement, the import statement must come before package statement.
c)    A Java file has at least one class defined.
d)    If a Java file has a package statement, it must be the first statement (except comments).


What happens when the following program is compiled and then the command "java check it out" is executed. Select the one correct answer.

class check {
    public static void main(String args[]) {
        System.out.println(args[args.length-2]);
    }
}


a)    The program does not compile.
b)    The program compiles but generates ArrayIndexOutOfBoundsException exception.
c)    The program prints java
d)    The program prints check
e)    The program prints it
f)    The program prints out


What all gets printed when the following code is compiled and run. Select the three correct answers.

class test {
    public static void main(String args[]) {
        int i[] = {0,1};
        try {
            i[2] = i[0] + i[1];
        }
        catch(ArrayIndexOutOfBoundsException e1) {
            System.out.println("1");
        }
        catch(Exception e2) {
            System.out.println("2");
        }
        finally {
            System.out.println(3);
        }
        System.out.println("4"); 
     }
}


a)    1
b)    2
c)    3
d)    4


A program needs to store the name, salary, and age of employees in years. Which of the following data types should be used to create the Employee class. Select the three correct answers.
a)    char
b)    boolean
c)    Boolean
d)    String
e)    int
f)    double


To make a variable defined in a class accessible only to methods defined in the classes in same package, which of the following keyword should be used. Select the one correct answer.
a)    By using the keyword package before the variable.
b)    By using the keyword private before the variable.
c)    By using the keyword protected before the variable.
d)    By using the keyword public before the variable.
e)    The variable should not be preceded by any of the above mentioned keywords.


In implementing two classes Employee and Manager, such that each Manager is an Employee, what should be the relationship between these classes. Select the one correct answer.
a)    Employee should be the base class of Manager class.
b)    Manager should be the base class of Employee class.
c)    Manager class should include the Employee class as a data member.
d)    Employee class should include Manager class as a data member.
e)    The Manager and Employee should not have any relationship.


Select the one most appropriate answer. What is the purpose of method parseInt defined in Integer class.
a)    The method converts an integer to a String.
b)    The method is used to convert String to an integer, assuming that the String represents an integer.
c)    The method is used to convert String to Integer class, assuming that the String represents an integer.
d)    The method converts the Integer object to a String.


What should be done to invoke the run() method on a thread for an object derived from the Thread class. Select the one correct answer.
a)    The run() method should be directly invoked on the Object.
b)    The start() method should be directly invoked on the Object.
c)    The init() method should be directly invoked on the Object.
d)    The creation of the object using the new operator would create a new thread and invoke its run() method.


What is the default priority of a newly created thread.
a)    MIN_PRIORITY (which is defined as 1 in the Thread class.)
b)    NORM_PRIORITY (which is defined as 5 in the Thread class.)
c)    MAX_PRIORITY (which is defined as 10 in the Thread class.)
d)    A thread inherits the priority of its parent thread.
The remaining questions are from AWT and related topics, and are not relevant for SCJP 1.4 .


Which of following correctly describes the functionality of the method drawRect(int a, int b, int c, int d) defined in jawa.awt.Graphics class. Select the one correct option.
a)    Draws the outline of a rectangle with a, b being the x,y co-ordinates of top left corner, and c,d being the x,y co-ordinates of the bottom right corner.
b)    Draws the outline of a rectangle with a, b being the x,y co-ordinates of top left corner, and c,d being the width and height of the rectangle.
c)    Draws a filled rectangle with a, b being the x,y co-ordinates of top left corner, and c,d being the x,y co-ordinates of the bottom right corner.
d)    Draws a filled rectangle with a, b being the x,y co-ordinates of top left corner, and c,d being the width and height of the rectangle.


Which Listener interface must be implemented by a class responsible for handling mouse clicks on buttons?


The getSource method defined in the EventObject class returns the source of an event. What is the return type of this getSource method?
a)    EventObject
b)    Event
c)    Object
d)    Component
e)    Button


The focusLost method is defined in FocusListener interface and is executed when a control loses focus. What is the argument of focusLost method?


Which of the following is the super class of these classes - ContainterEvent, FocusEvent, InputEvent, PaintEvent, WindowEvent. Select the one correct answer.
a)    ActionEvent
b)    AdjustmentEvent
c)    ComponentEvent
d)    ItemEvent
e)    TextEvent
f)    Event


Which of these are adapter classes. Select the three correct answers.
a)    ComponentAdapter
b)    ItemAdapter
c)    ActionAdapter
d)    KeyAdapter
e)    ContainerAdapter


Which of the following statements about layout managers is true. Select the one correct answer.
a)    FlowLayout places components left-aligned in a row (by default) and when there is no space in a row, another row is started.
b)    FlowLayout provides a constructor Flowlayout(int align, int x, int y), where x and y are the coordinates of the first component being added.
c)    The FlowLayout is the default layout manager for Window class
d)    Default horizontal and vertical gaps of components placed using FlowLayout is 5 pixels.


Which of the following is true about BorderLayout. Select the two correct answers.
a)    The default layout manager for Applet class is BorderLayout.
b)    BorderLayout places components in North, South, East and West first and then the remaining space is occupied by the Center component.
c)    When a component is added in BorderLayout using the add method, it is placed in the center by default.
d)    The BorderLayout always honors the size of components provided by the program.


Which of these is true about the GridBagLayout. Select the one correct answer.
a)    The weightx and weighty fields of GridBagConstraints specify how many column and rows each component occupies.
b)    The gridwidth and gridheight constraints of GridBagConstraints specify the width and height in pixels of each cell.
c)    GridBagLayout is the default layout manager of the Frame class.
d)    The gridx and gridy parameters of GridBagConstraints define the column and row position of the upper left corner of the component.




Answers to Sample Test 2


1)    c, d, f
2)    c. The main method must be static and return void. Hence a and b are incorrect. It must take an array of String as argument. Hence e and f are incorrect. As Java is case sensitive, d is incorrect.
3)    a, d
4)    List
5)    e. The collection interface Map has two implementation HashMap and Hashtable.
6)    Local variables are not initialized by default. They must be initialized before they are used.
7)    d. The variable i gets initialized to zero. The while loop does not get executed.
8)    During various iterations of three loops, the only time i, j and k have same values are when all of them are set to 2.
9)    0x17 or 0X17.
10)    e. The statement "i=2" evaluates to 2. The expression within the if block must evaluate to a boolean.
11)    e. The range of short primitive type is -32768 to 32767.
12)    c,d. Java does not allow casts between boolean values and any numeric types. Hence a is incorrect. Assigning double to a float requires an explicit cast. Hence b and e are incorrect.
13)    a
14)    e
15)    Both Strings test and test2 contain "abcd" . They are however located at different memory addresses. Hence test == test2 returns false, and test.equals(test2) returns true.
16)    The for loop does not get executed even once as the condition (i < 0) fails in the first iteration. In the switch statement, the statement j = j +1; gets executed, setting j to 1. As there is no break after this case, the next statement also gets executed setting j to 3.
17)    5050. The recursive function xyz essentially sums up numbers 1 to num. This evaluates to (num * (num + 1))/2.
18)    Java supports assignment of one array to another. Hence b is incorrect. Array elements are indexed from 0. Hence c is incorrect. A method that accesses array elements out of its range does not generate a compilation error. Hence d is incorrect.
19)    array.length gives the number of elements in the array. As indexes in Java start from 0, d is the correct answer.
20)    In the invocation of call_array, the first element is invoked using call-by-value, and the second using call-by-reference.
21)    import statement, package statement and class definitions are all optional in a file. Hence a and c are incorrect. If both import and package statements are present in a file, then package statement must appear before the import statement. Hence b is incorrect.
22)    The args array consists of two elements "it" and "out". args.length is set to two.
23)    a,c,d. The exception ArrayIndexOutOfBoundsException is generated as the main method tries to access i[2]. Hence 1 gets printed. After this finally block gets excuted, before the program exits.
24)    d,e,f
25)    A data member that does not have public/protected/private is accessible to all methods in the same package.
26)    The Manager and Employee share as "is a" relationship - A Manager is an Employee. This is captured by making Employee the base class of Manager.
27)    The method int parseInt(Sting s) returns the integer value corresponding to input String, assuming that the input string represents an integer in base 10.
28)    The start() method invokes the run() method when the thread is ready to execute.
29)    d
30)    b. drawRect method draws the outline of a rectangle. The last two arguments are width and height of the rectangle.
31)    ActionListener
32)    The getSource method returns a reference to the object where the event initially occurred.
33)    FocusEvent. A class implementing FocusListener interface must implement the following method -
34)    public void focusLost(FocusEvent)
35)    public void focusGained(FocusEvent)

36)    c
37)    a,d,e. There are no adapter classes corresponding to the following interfaces - ActionListener, ItemListener, AdjustmentListener, and TextListener.
38)    The default alignment for FlowLayout is CENTER. Hence a is incorrect. The default Layout Manager for Window class is BorderLayout. Hence c is incorrect. X and y in option b indicate horizontal and vertical gaps between components.
39)    b,c. The default Layout Manager for Applet class is FlowLayout. Hence a is incorrect. BorderLayout grows all components to fill the space available. Hence d is incorrect.
40)    d. The weightx and weighty specify how the size of a cell should change when the container exceeds the preferred size of component. Hence a is not correct. gridwidth and gridheight specify how many columns and rows the component specifies. So b is incorrect. BorderLayout is the default layout manager for Frame class.
home | tutorial | questions | test 1  Questions on Classes

What gets displayed on the screen when the following program is compiled and run. Select the one correct answer.

protected class example {
    public static void main(String args[]) {
        String test = "abc";
        test = test + test;
        System.out.println(test);
    }
}


a)    The class does not compile because the top level class cannot be protected.
b)    The program prints "abc"
c)    The program prints "abcabc"
d)    The program does not compile because statement "test = test + test" is illegal.
A top level class may have only the following access modifier. Select the one correct answer.
a)    package
b)    friendly
c)    private
d)    protected
e)    public
Write down the modifier of a method that makes the method available to all classes in the same package and to all the subclasses of this class.
Select the one most appropriate answer. A top level class without any modifier is accessible to -
a)    any class
b)    any class within the same package
c)    any class within the same file
d)    any subclass of this class.
Is this True or False. In Java an abstract class cannot be sub-classed.
Is this True or False. In Java a final class must be sub-classed before it can be used.
Which of the following are true. Select the three correct answers.
a)    A static method may be invoked before even a single instance of the class is constructed.
b)    A static method cannot access non-static methods of the class.
c)    Abstract modifier can appear before a class or a method but not before a variable.
d)    final modifier can appear before a class or a variable but not before a method.
e)    Synchronized modifier may appear before a method or a variable but not before a class.
Answers to questions on classes in Java

1)    a
2)    e
3)    protected
4)    b
5)    False
6)    False
7)    a, b, c. final modifier may appear before a method, a variable or before a class.


Questions on AWT
This topic is part of SCJP 1.2 exam but not SCJP 1.4 exam.
Which of the following classes are derived from the Container class. Select the four correct answers.
a)    Component
b)    Panel
c)    java.applet.Applet
d)    Dialog
e)    Frame
f)    MenuComponent
Which of the following classes are derived from the Component class. Select the four correct answers.
a)    Container
b)    Window
c)    List
d)    MenuItem
e)    Choice
Name the class used to represent a GUI application window, which is optionally resizable and can have a title bar, an icon, and menus. Select the one correct answer.
a)    Window
b)    Panel
c)    Dialog
d)    Frame
Which abstract class is the super class of all menu related classes.
Which of these classes can be added to a Frame component. Select the three correct answers.
a)    Menu
b)    Button
c)    PopupMenu
d)    Window
e)    List
Which class can be used to represent a checkbox with a textual label that can appear in a menu. Select the one correct answer.
a)    MenuBar
b)    MenuItem
c)    CheckboxMenuItem
d)    Menu
e)    CheckBox
Which of these classes can be added to any Container class, using the add method defined in Container class. Select the two correct answers.
a)    Button
b)    CheckboxMenuItem
c)    Menu
d)    Canvas
Answers to questions on AWT

1)    b, c, d, e
2)    a, b, c, e
3)    d
4)    MenuComponent
5)    b, c, e
6)    c
7)    a, d


Questions on Collections

TreeMap class is used to implement which collection interface. Select the one correct answer.
a)    Set
b)    SortedSet
c)    List
d)    Tree
e)    SortedMap
Name the Collection interface implemented by the Vector class.
Name the Collection interface implemented by the Hashtable class.
Name the Collection interface implemented by the HashSet class.
Which of these are interfaces in the collection framework. Select the two correct answers.
a)    Set
b)    List
c)    Array
d)    Vector
e)    LinkedList
Which of these are interfaces in the collection framework. Select the two correct answers.
a)    HashMap
b)    ArrayList
c)    Collection
d)    SortedMap
e)    TreeMap
What is the name of collection interface used to maintain non-unique elements in order.
What is the name of collection interface used to maintain unique elements.
What is the name of collection interface used to maintain mappings of keys to values.
Is this true or false. Map interface is derived from the Collection interface.
a)    True
b)    False
Answers to questions on Collections

1)    e
2)    List
3)    Map
4)    Set
5)    a,b
6)    c,d
7)    List
8)    Set
9)    Map
10)    b
11)    Advertisement

March Mini Quiz
New to Java Programming Center
 
What is the intial layout manager of a JApplet?
  A.  FlowLayout
  B.  OverlayLayout
  C.  GridLayout
  D.  BorderLayout
  E.  AppletLayout



If you add a component to the content pane of a JApplet and don't specify any constraints, what happens to it?
  A.  The add method rejects the operation.
  B.  The add method adds the component to the container, but doesn't place it in any of the areas of the content pane.
  C.  The add method adds the component to the Center area of the pane.
  D.  There is no way to call add without any constraints.



Where can you place a JMenuBar in a Swing applet?
  A.  Top of applet
  B.  Left side of applet
  C.  Right side of applet
  D.  Bottom of applet
  E.  Any of the above



Should speed keys be used in applet menus?
  A.  Yes
  B.  No
  C.  It depends



Do I have to use the HTML Converter to add a Swing applet on my web page?
  A.  Yes
  B.  No


 
Java Technology Fundaments Newsletters
March Quiz Answers
(March 2003)
1. What is the intial layout manager of a JApplet? 
A is incorrect Answer (D): Even though you don't add components directly to a Swing applet, instead adding them to the content pane, the default layout manager of a JApplet really is BorderLayout.
 
2. If you add a component to the content pane of a JApplet and don't specify any constraints, what happens to it? 
A is incorrect Answer (C): When there are no constraints specified, a JApplet will place added components into the center area of the BorderLayout for its content pane.
 
3. Where can you place a JMenuBar in a Swing applet? 
B is incorrect Answer (E): While the setJMenuBar method will add a menu to the top of an applet, since JMenuBar is a component, it can be added anywhere that a component can be used. 
4. Should speed keys be used in applet menus? 
C is correct! Answer (C): While Swing permits menu items to have mnemonics associated with them, their use should probably be avoided, except where their usage is obvious. Speed keys only work when an applet has input focus. Thus, it may be confusing to the user to sometimes activate the menu associated with an applet and other times activate the menu associated wit the browser. 

 5. Do I have to use the HTML Converter to add a Swing applet on my web page?
A is incorrect Answer (B): Early versions of the Java Plugin required a tool called the HTML Converter to mangle the HTML that loaded a web page with the APPLET tag. Thankfully, that tool is no longer needed and you can use the APPLET tag directly, without the mangling.