C interview questions

Top most important C interview questions and answers by Experts:

Here is a list of Top most important C interview questions and answers by Experts.If you want to download C interview questions pdf free ,you can register with RVH techguru. Our experts prepared these C interview questions to accommodate freshers level to most experienced level technical interviews.

If you want to become an expert in C ,Register for C online training here.

 

1) How do you construct an increment statement or decrement statement in C?
There are actually two ways you can do this. One is to use the increment operator ++ and decrement operator –. For example, the statement “x++” means to increment the value of x by 1. Likewise, the statement “x –” means to decrement the value of x by 1. Another way of writing increment statements is to use the conventional + plus sign or – minus sign. In the case of “x++”, another way to write it is “x = x +1?.

2) Some coders debug their programs by placing comment symbols on some codes instead of deleting it. How does this aid in debugging?
Placing comment symbols /* */ around a code, also referred to as “commenting out”, is a way of isolating some codes that you think maybe causing errors in the program, without deleting the code. The idea is that if the code is in fact correct, you simply remove the comment symbols and continue on. It also saves you time and effort on having to retype the codes if you have deleted it in the first place.

3) What is the equivalent code of the following statement in WHILE LOOP format?
[c]
for (a=1; a<=100; a++)
printf (“%d\n”, a * a);
[/c]
[c]
a=1;
while (a<=100) {
printf (“%d\n”, a * a);
a++;
}
[/c]

4) What is spaghetti programming?
Spaghetti programming refers to codes that tend to get tangled and overlapped throughout the program. This unstructured approach to coding is usually attributed to lack of experience on the part of the programmer. Spaghetti programing makes a program complex and analyzing the codes difficult, and so must be avoided as much as possible.

5) In C programming, how do you insert quote characters (‘ and “) into the output screen?
This is a common problem for beginners because quotes are normally part of a printf statement. To insert the quote character as part of the output, use the format specifiers \’ (for single quote), and \” (for double quote).

6) What is the use of a ‘\0′ character?
It is referred to as a terminating null character, and is used primarily to show the end of a string value.

7) What is the difference between the = symbol and == symbol?
The = symbol is often used in mathematical operations. It is used to assign a value to a given variable. On the other hand, the == symbol, also known as “equal to” or “equivalent to”, is a relational operator that is used to compare two values.

8) Which of the following operators is incorrect and why? ( >=, <=, <>, ==)
<> is incorrect. While this operator is correctly interpreted as “not equal to” in writing conditional statements, it is not the proper operator to be used in C programming. Instead, the operator != must be used to indicate “not equal to” condition.

9) Can the curly brackets { } be used to enclose a single line of code?
While curly brackets are mainly used to group several lines of codes, it will still work without error if you used it for a single line. Some programmers prefer this method as a way of organizing codes to make it look clearer, especially in conditional statements.

10) What are header files and what are its uses in C programming?
Header files are also known as library files. They contain two essential things: the definitions and prototypes of functions being used in a program. Simply put, commands that you use in C programming are actually functions that are defined from within each header files. Each header file contains a set of functions. For example: stdio.h is a header file that contains definition and prototypes of commands like printf and scanf.

11) Can I use “int” data type to store the value 32768? Why?
No. “int” data type is capable of storing values from -32768 to 32767. To store 32768, you can use “long int” instead. You can also use “unsigned int”, assuming you don’t intend to store negative values.

12) Can two or more operators such as \n and \t be combined in a single line of program code
Yes, it’s perfectly valid to combine operators, especially if the need arises. For example: you can have a code like ” printf (“Hello\n\n\’World\’”) ” to output the text “Hello” on the first line and “World” enclosed in single quotes to appear on the next two lines.

13) Why is it that not all header files are declared in every C program?
The choice of declaring a header file at the top of each C program would depend on what commands/functions you will be using in that program. Since each header file contains different function definitions and prototype, you would be using only those header files that would contain the functions you will need. Declaring all header files in every program would only increase the overall file size and load of the program, and is not considered a good programming style.

14) When is the “void” keyword used in a function?
When declaring functions, you will decide whether that function would be returning a value or not. If that function will not return a value, such as when the purpose of a function is to display some outputs on the screen, then “void” is to be placed at the leftmost part of the function header. When a return value is expected after the function execution, the data type of the return value is placed instead of “void”.

15) What are compound statements?
Compound statements are made up of two or more program statements that are executed together. This usually occurs while handling conditions wherein a series of statements are executed when a TRUE or FALSE is evaluated. Compound statements can also be executed within a loop. Curly brackets { } are placed before and after compound statements.

16) Write a loop statement that will show the following output:
1
12
123
1234
12345
[c]
for (a=1; a<=5; i++) {
for (b=1; b<=a; b++)
printf(“%d”,b);
printf(“\n”);
}
[/c]

17) What is wrong in this statement? scanf(“%d”,whatnumber);
An ampersand & symbol must be placed before the variable name whatnumber. Placing & means whatever integer value is entered by the user is stored at the “address” of the variable name. This is a common mistake for programmers, often leading to logical errors.

18) How do you generate random numbers in C?
Random numbers are generated in C using the rand() command. For example: anyNum = rand() will generate any integer number beginning from 0, assuming that anyNum is a variable of type integer.

19) What could possibly be the problem if a valid function name such as tolower() is being reported by the C compiler as undefined?
The most probable reason behind this error is that the header file for that function was not indicated at the top of the program. Header files contain the definition and prototype for functions and commands used in a C program. In the case of “tolower()”, the code “#include ” must be present at the beginning of the program.

20) What does the format %10.2 mean when included in a printf statement?
This format is used for two things: to set the number of spaces allotted for the output number and to set the number of decimal places. The number before the decimal point is for the allotted space, in this case it would allot 10 spaces for the output number. If the number of space occupied by the output number is less than 10, addition space characters will be inserted before the actual output number. The number after the decimal point sets the number of decimal places, in this case, it’s 2 decimal spaces.

21) What is wrong with this statement? myName = “Robin”;
You cannot use the = sign to assign values to a string variable. Instead, use the strcpy function. The correct statement would be: strcpy(myName, “Robin”);

22) How do you determine the length of a string value that was stored in a variable?
To get the length of a string value, use the function strlen(). For example, if you have a variable named FullName, you can get the length of the stored string value by using this statement: I = strlen(FullName); the variable I will now have the character length of the string value.

23) Is it possible to initialize a variable at the time it was declared?
Yes, you don’t have to write a separate assignment statement after the variable declaration, unless you plan to change it later on. For example: char planet[15] = “Earth”; does two things: it declares a string variable named planet, then initializes it with the value “Earth”.

24) What are the different file extensions involved when programming in C?
Source codes in C are saved with .C file extension. Header files or library files have the .H file extension. Every time a program source code is successfully compiled, it creates an .OBJ object file, and an executable .EXE file.

25) What are reserved words?
Reserved words are words that are part of the standard C language library. This means that reserved words have special meaning and therefore cannot be used for purposes other than what it is originally intended for. Examples of reserved words are int, void, and return.

26) What are linked list?
A linked list is composed of nodes that are connected with another. In C programming, linked lists are created using pointers. Using linked lists is one efficient way of utilizing memory for storage.

27) What are binary trees?
Binary trees are actually an extension of the concept of linked lists. A binary tree has two pointers, a left one and a right one. Each side can further branch to form additional nodes, which each node having two pointers as well.

28) Not all reserved words are written in lowercase. TRUE or FALSE?
FALSE. All reserved words must be written in lowercase; otherwise the C compiler would interpret this as unidentified and invalid.

29) What is wrong with this program statement? void = 10;
The word void is a reserved word in C language. You cannot use reserved words as a user-defined variable.

30) Is this program statement valid? INT = 10.50;
Assuming that INT is a variable of type float, this statement is valid. One may think that INT is a reserved word and must not be used for other purposes. However, recall that reserved words are express in lowercase, so the C compiler will not interpret this as a reserved word.

31) What is a newline escape sequence?
A newline escape sequence is represented by the \n character. This is used to insert a new line when displaying data in the output screen. More spaces can be added by inserting more \n characters. For example, \n\n would insert two spaces. A newline escape sequence can be placed before the actual output expression or after.

32) What is output redirection?
It is the process of transferring data to an alternative output source other than the display screen. Output redirection allows a program to have its output saved to a file. For example, if you have a program named COMPUTE, typing this on the command line as COMPUTE >DATA can accept input from the user, perform certain computations, then have the output redirected to a file named DATA, instead of showing it on the screen.

33) What is the difference between functions abs() and fabs()?
These 2 functions basically perform the same action, which is to get the absolute value of the given value. Abs() is used for integer values, while fabs() is used for floating type numbers. Also, the prototype for abs() is under , while fabs() is under .

34) Write a simple code fragment that will check if a number is positive or negative.
[c]
If (num>=0)
printf(“number is positive”);
else
printf (“number is negative”);
[/c]

35) What does the function toupper() do?
It is used to convert any letter to its upper case mode. Toupper() function prototype is declared in . Note that this function will only convert a single character, and not an entire string.

36) Which function in C can be used to append a string to another string?
The strcat function. It takes two parameters, the source string and the string value to be appended to the source string.

37) Dothese two program statements perform the same output? 1) scanf(“%c”, &letter); 2) letter=getchar()
Yes, they both do the exact same thing, which is to accept the next key pressed by the user and assign it to variable named letter.

38) What is the difference between text files and binary files?
Text files contain data that can easily be understood by humans. It includes letters, numbers and other characters. On the other hand, binary files contain 1s and 0s that only computers can interpret.

39) is it possible to create your own header files?
Yes, it is possible to create a customized header file. Just include in it the function prototypes that you want to use in your program, and use the #include directive followed by the name of your header file.

40) What is dynamic data structure?
Dynamic data structure provides a means for storing data more efficiently into memory. Using dynamic memory allocation, your program will access memory spaces as needed. This is in contrast to static data structure, wherein the programmer has to indicate a fix number of memory space to be used in the program.

41) The % symbol has a special use in a printf statement. How would you place this character as part of the output on the screen?
You can do this by using %% in the printf statement. For example, you can write printf(“10%%”) to have the output appear as 10% on the screen.

42) What are the advantages and disadvantages of a heap?
Storing data on the heap is slower than it would take when using the stack. However, the main advantage of using the heap is its flexibility. That’s because memory in this structure can be allocated and remove in any particular order. Slowness in the heap can be compensated if an algorithm was well designed and implemented.
43) What will be the output of printf(“%d”)?
The ideal form of printf is printf(“%d”,x); where x is an integer variable. Executing this statement will print the value of x. But here, there is no variable is provided after %d so compiler will show garbage value. The reason is a bit tricky.
When access specifiers are used in printf function, the compiler internally uses those specifiers to access the arguments in the argument stack. In ideal scenario compiler determines the variable offset based on the format specifiers provided. If we write printf(“%d”, x) then compiler first accesses the first specifier which is %d and depending on the that the offset of variable x in the memory is calculated. But the printf function takes variable arguments.
The first argument which contains strings to be printed or format specifiers is mandatory. Other than that, the arguments are optional.So, in case of only %d used without any variable in printf, the compiler may generate warning but will not cause any error. In this case, the correct offset based on %d is calculated by compiler but as the actual data variable is not present in that calculated location of memory, the printf will fetch integer size value and print whatever is there (which is garbage value to us).
44) What is the return values of printf and scanf?
The printf function upon successful return, returns the number of characters printed in output device. So, printf(“A”) will return 1. The scanf function returns the number of input items successfully matched and assigned, which can be fewer than the format specifiers provided. It can also return zero in case of early matching failure.
45) How to free a block of memory previously allocated without using free?
If the pointer holding that memory address is passed to realloc with size argument as zero (like realloc(ptr, 0)) the the memory will be released.
46) How can you print a string containing ‘%’ in printf?
There are no escape sequence provided for ‘%’ in C. To print ‘%’ one should use ‘%%’, like –
printf(“He got 90%% marks in math”);
47) What is use of %n in printf()?
According to man page “the number of characters written so far is stored into the integer. indicated by the int * (or variant) pointer argument.“. Meaning if we use it in printf, it will get the number of characters already written until %n is encountered and this number will stored in the variable provided. The variable must be an integer pointer.
#include<stdio.h>
main()
{
int c;
printf(“Hello%n world “,&c);
printf(“%d”, c);
}
Above program will print ‘Hello world 5 “ as Hello is 5 letter.
48) Swap two variables without using any control statement ?
We can swap variable using 2 methods. First method is as given below
#include <stdio.h>
main()
{
int a = 6;
int b = 10;
a = a + b;
b = a – b;
a = a – b;
printf(“a: %d, b: %d\n”, a, b);
}
Second method to swap variables is given below
#include <stdio.h>
main()
{
int a = 6;
int b = 10;
a ^= b;
b ^= a;
a ^= b;
printf(“a: %d, b: %d\n”, a, b);
}
49) How to call a function before main()?
To call a function pragma startup directive should be used. Pragma startup can be used like this –
#pragma startup fun
void fun()
{
printf(“In fun\n”);
}
main()
{
printf(“In main\n”);
}
The output of the above program will be –
In fun
In main
But this pragma directive is compiler dependent. Gcc does not support this. So, it will ignore the startup directive and will produce no error. But the output in that case will be –
In main
50) What is rvalue and lvalue?
You can think lvalue as a left side operant in an assignment and rvalue is the right. Also, you can remember lavlue as location. So, the lvalue means a location where you can store any value. Say, for statement i = 20, the value 20 is to be stored in the location or address of the variable i. 20 here is rvalue. Then the 20 = I, statement is not valid. It will result in compilation error “lvalue required” as 20 does not represent any location.
51) Which is better #define or enum?
• Enum values can be automatically generated by compiler if we let it. But all the define values are to be mentioned specifically.
• Macro is preprocessor, so unlike enum which is a compile time entity, source code has no idea about these macros. So, the enum is better if we use a debugger to debug the code.
• If we use enum values in a switch and the default case is missing, some compiler will give a warning.
• Enum always makes identifiers of type int. But the macro let us choose between different integral types.
• Macro does not specifically maintain scope restriction unlike enum. For example –
#include <stdio.h>
main()
{
{
#define A 10
printf(“first A: %d\n”, A);
}
{
printf(“second A: %d\n”, A);
}
}
Above program will print –
first A: 10
second A: 10
52) What is the difference between const char* p and char const* p?
In const char* p, the character pointed by pointer variable p is constant. This value can not be changed but we can initialize p with other memory location. It means the character pointed by p is constant but not p. In char const* p, the pointer p is constant not the character referenced by it. So we can’t assign p with other location but we can change the value of the character pointed by p.
53) What is the point of using malloc(0)?
According to C standard, “ If the size of the space requested is zero, the behavior is implementation defined: either a null pointer is returned, or the behavior is as if the size were some nonzero value, except that the returned pointer shall not be used to access an object”. But there is a benefit of this. The pointer return after malloc(0) will be valid pointer and can be deallocated using free() and it will not crash the program.
54) What is function pointer?
Function pointer, as the name suggests, points to a function. We can declare a function pointer and point to a function. After that using that function pointer we can call that function. Let’s say, we have a function Hello which has definition like this –
void Hello(int)
The pointer to that function will look like –
void (*ptr)(int);
Here, ptr is a function pointer that can point to function with no return type and one integer argument. After declaration, we can point to function Hello like this –
void (*ptr)(int) = NULL;
ptr = Hello;
After that we can call that function like this –
(*ptr)(30);
55) Declare a function pointer that points to a function which returns a function pointer ?
To understand this concept, let us look at the following example.
#include<stdio.h>
void Hello();
typedef void (*FP)();

FP fun(int);

main()
{
FP (*ptr)(int) = NULL;
FP p;
ptr = fun;
p = (*fun)(30);
(*p)();
}

void Hello()
{
printf(“Hello\n”);
}

FP fun(int a)
{
FP p = Hello;
printf(“Number is : %d\n”, a);
return p;
}
In this program, we have a function Hello with no return type and no argument. The function fun takes an integer argument and returns a function pointer that can point to Hello(). First we have typdef the function pointer which can point to a function with no return type and argument with identifier FP. That way it will be easier to define the required function pointer. If we avoid typedef the required function pointer (ptr) will look like this –
void (*(*ptr)())(int)
56) What is indirection?
In C when we use variable name to access the value it is direct access. If we use pointer to get the variable value, it is indirection.
57) Can math operations be performed on a void pointer?
No. Pointer addition and subtraction means advancing the pointer by a number of elements. But in case of a void pointer, we don’t know fpr sure what it’s pointing to, so we don’t know the size of what it’s pointing to. That is why pointer arithmetic can not be used on void pointers.

 

 

C++ interview questions

Top most important C++ interview questions and answers by Experts

Here is a list of Top most important C++ interview questions and answers by Experts.If you want to download C++ interview questions pdf free ,you can register with RVH techguru. Our experts prepared these C++ interview questions to accommodate freshers level to most experienced level technical interviews.

If you want to become an expert in C++ ,Register for C++ online training here.

 

1.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

2.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.

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

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

5.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

6.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.

7.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); 

8.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.

9.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.

10.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.

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

12.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.

13.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. 

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

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

16.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.

17.What’s the output of the following program? Why?
#include <stdio.h>

main()
{
typedef union
{
int a;
char b[10];
float c;
}
Union;

Union x,y = {100};
x.a = 50;
strcpy(x.b,\”hello\”);
x.c = 21.50;

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

Given inputs X, Y, Z and operations | and & (meaning bitwise OR and AND, respectively)
What is output equal to in 
output = (X & Y) | (X & Z) | (Y & Z)

18.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.

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

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

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

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

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

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

23.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.

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

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

25.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.

26.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.

27.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.

28.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.

29.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.

30.What is indirection?
In C when we use variable name to access the value it is direct access. If we use pointer to get the variable value, it is indirection.

31.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)……

32.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.

33.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.

34.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);

}

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

36.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.

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

38.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);

39.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.

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

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

42.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.

43.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.”

44.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.

45.When is a template a better solution than a base class? 
When you are designing a generic class to contain or otherwise manage objects of other types, when the format and behavior of those other types are unimportant to their containment or management, and particularly when those other types are unknown (thus, the generosity) to the designer of the container or manager class.

46.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.

47.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.

48.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.

49.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.

50.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.

51.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.

52.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

53.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 

Answer3
In C++
[$]> g++ point.c
point.c: In function `int main()’:
point.c:4: error: invalid conversion from `int’ to `char*’
point.c:5: error: invalid conversion from `int’ to `long int*’ 

in C
———————————–
[$] etc > gcc point.c
point.c: In function `main’:
point.c:4: warning: initialization makes pointer from integer without a cast
point.c:5: warning: initialization makes pointer from integer without a cast
[$] etc > ./a.exe
2001 2004

54.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. 

55.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.

56.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.

57.What are the defining traits of an object-oriented language? 
The defining traits of an object-oriented langauge are:
* encapsulation
* inheritance
* polymorphism

58.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”<<average<<endl;

return 0;
}

59.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.

60.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.

61.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

62.What is the need for a Virtual Destructor ? 
Destructors are declared as virtual because if do not declare it as virtual the base class destructor will be called before the derived class destructor and that will lead to memory leak because derived class’s objects will not get freed.Destructors are declared virtual so as to bind objects to the methods at runtime so that appropriate destructor is called.

63.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
}

64.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.

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

66.What is a modifier? 
A modifier, also called a modifying function is a member function that changes the value of  at least one data member. In other words, an operation that modifies the state of an object. Modifiers are also known as ‘mutators’. Example: The function mod is a modifier in the following code snippet:

class test
{
int x,y;
public:
test()
{
x=0; y=0;
}
void mod()
{
x=10;
y=15;
}
};

67.What is an accessor? 
An accessor is a class operation that does not modify the state of an object. The accessor functions need to be declared as const operations

68.Differentiate between a template class and class template.
Template class: A generic definition or a parameterized class not instantiated until the client provides the needed information. It’s jargon for plain templates. Class template: A class template specifies how individual classes can be constructed much like the way a class specifies how individual objects can be constructed. It’s jargon for plain classes.

69.When does a name clash occur? 
A name clash occurs when a name is defined in more than one place. For example., two different class libraries could give two different classes the same name. If you try to use many class libraries at the same time, there is a fair chance that you will be unable to compile or link the program because of name clashes.

70.Define namespace. 
It is a feature in C++ to minimize name collisions in the global name space. This namespace keyword assigns a distinct name to a library that allows other libraries to use the same identifier names without creating any name collisions. Furthermore, the compiler uses the namespace signature for differentiating the definitions.

71.What is the use of ‘using’ declaration. ?
A using declaration makes it possible to use a name from a namespace without the scope operator.

72.What is an Iterator class ? 
A class that is used to traverse through the objects maintained by a container class. There are five categories of iterators: input iterators, output iterators, forward iterators, bidirectional iterators, random access. An iterator is an entity that gives access to the contents of a container object without violating encapsulation constraints. Access to the contents is granted on a one-at-a-time basis in order. The order can be storage order (as in lists and queues) or some arbitrary order (as in array indices) or according to some ordering relation (as in an ordered binary tree). The iterator is a construct, which provides an interface that, when called, yields either the next element in the container, or some value denoting the fact that there are no more elements to examine. Iterators hide the details of access to and update of the elements of a container class.
The simplest and safest iterators are those that permit read-only access to the contents of a container class. 

73.What is an incomplete type? 
Incomplete types refers to pointers in which there is non availability of the implementation of the referenced location or it points to some location whose value is not available for modification. 

int *i=0x400 // i points to address 400
*i=0; //set the value of memory location pointed by i. 

Incomplete types are otherwise called uninitialized pointers.

74.What is a dangling pointer? 
A dangling pointer arises when you use the address of an object after
its lifetime is over. This may occur in situations like returning
addresses of the automatic variables from a function or using the
address of the memory block after it is freed. The following
code snippet shows this:

class Sample
{
public:
int *ptr;
Sample(int i)
{
ptr = new int(i);
}

~Sample()
{
delete ptr;
}
void PrintVal()
{
cout << “The value is ” << *ptr;
}
};

void SomeFunc(Sample x)
{
cout << “Say i am in someFunc ” << endl;
}

int main()
{
Sample s1 = 10;
SomeFunc(s1);
s1.PrintVal();
}

In the above example when PrintVal() function is
called it is called by the pointer that has been freed by the
destructor in SomeFunc.

75.Differentiate between the message and method.
Message:

* Objects communicate by sending messages to each other.
* A message is sent to invoke a method.

Method
* Provides response to a message.
* It is an implementation of an operation.

76.What is an adaptor class or Wrapper class? 
A class that has no functionality of its own. Its member functions hide the use of a third party software component or an object with the non-compatible interface or a non-object-oriented implementation.

77.What is a Null object? 
It is an object of some class whose purpose is to indicate that a real object of that class does not exist. One common use for a null object is a return value from a member function that is supposed to return an object with some specified properties but cannot find such an object. 

78.What is class invariant? 
A class invariant is a condition that defines all valid states for an object. It is a logical condition to ensure the correct working of a class. Class invariants must hold when an object is created, and they must be preserved under all operations of the class. In particular all class invariants are both preconditions and post-conditions for all operations or member functions of the class.

79.What do you mean by Stack unwinding? 
It is a process during exception handling when the destructor is called for all local objects between the place where the exception was thrown and where it is caught.

80.Define precondition and post-condition to a member function. 
Precondition: A precondition is a condition that must be true on entry to a member function. A class is used correctly if preconditions are never false. An operation is not responsible for doing anything sensible if its precondition fails to hold. For example, the interface invariants of stack class say nothing about pushing yet another element on a stack that is already full. We say that isful() is a precondition of the push operation. Post-condition: A post-condition is a condition that must be true on exit from a member function if the precondition was valid on entry to that function. A class is implemented correctly if post-conditions are never false. For example, after pushing an element on the stack, we know that isempty() must necessarily hold. This is a post-condition of the push operation.

81.What are the conditions that have to be met for a condition to be an invariant of the class? 
* The condition should hold at the end of every constructor.
* The condition should hold at the end of every mutator (non-const) operation.

82.What are proxy objects? 
Objects that stand for other objects are called proxy objects or surrogates. 
template <class t=””>
class Array2D
{
public:
class Array1D
{
public:
T& operator[] (int index);
const T& operator[] (int index)const;
};

Array1D operator[] (int index);
const Array1D operator[] (int index) const;
};

The following then becomes legal:

Array2D<float>data(10,20);
cout<<data[3][6]; // fine

Here data[3] yields an Array1D object and the operator [] invocation on that object yields the float in position(3,6) of the original two dimensional array. Clients of the Array2D class need not be aware of the presence of the Array1D class. Objects of this latter class stand for one-dimensional array objects that, conceptually, do not exist for clients of Array2D. Such clients program as if they were using real, live, two-dimensional arrays. Each Array1D object stands for a one-dimensional array that is absent from a conceptual model used by the clients of Array2D. In the above example, Array1D is a proxy class. Its instances stand for one-dimensional arrays that, conceptually, do not exist.

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

84.What is an orthogonal base class? 
If two base classes have no overlapping methods or data they are said to be independent of, or orthogonal to each other. Orthogonal in the sense means that two classes operate in different dimensions and do not interfere with each other in any way. The same derived class may inherit such classes with no difficulty.

85.What is a node class?
A node class is a class that,

* relies on the base class for services and implementation,
* provides a wider interface to the users than its base class,
* relies primarily on virtual functions in its public interface
* depends on all its direct and indirect base class
* can be understood only in the context of the base class
* can be used as base for further derivation
* can be used to create objects.
A node class is a class that has added new services or functionality beyond the services inherited from its base class.

86.What is a container class? What are the types of container classes? 
A container class is a class that is used to hold objects in memory or external storage. A container class acts as a generic holder. A container class has a predefined behavior and a well-known interface. A container class is a supporting class whose purpose is to hide the topology used for maintaining the list of objects in memory. When a container class contains a group of mixed objects, the container is called a heterogeneous container; when the container is holding a group of objects that are all the same, the container is called a homogeneous container.

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

void reverselist(void)
{
if(head==0)
return;
if(head-<next==0)
return;
if(head-<next==tail)
{
head-<next = 0;
tail-<next = head;
}
else
{
node* pre = head;
node* cur = head-<next;
node* curnext = cur-<next;
head-<next = 0;
cur-<next = head;

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

curnext-<next = cur;
}
}

Answer2:

node* reverselist(node* head)
{
if(0==head || 0==head->next) 
//if head->next ==0 should return head instead of 0;
return 0;

{
node* prev = head;
node* curr = head->next;
node* next = curr->next;

for(; next!=0; )
{
curr->next = prev;
prev = curr;
curr = next;
next = next->next;
}
curr->next = prev;

head->next = 0;
head = curr;
}

return head;
}

88.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.

89.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.

90.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.

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

* a->b is a trivial functional dependency (b is a subset of a)
* a is a superkey for schema R

92.What is pure virtual function? 
A class is made abstract by declaring one or more of its virtual functions to be pure. A pure virtual function is one with an initializer of = 0 in its declaration 

93.Write a Struct Time where integer m, h, s are its members 
struct Time
{
int m;
int h;
int s;
};

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

95.What is the two main roles of Operating System? 
As a resource manager
As a virtual machine

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

97.Could you tell something about the Unix System Kernel? 
The kernel is the heart of the UNIX openrating system, it’s reponsible for controlling the computer’s resouces and scheduling user jobs so that each one gets its fair share of resources.

98.What are each of the standard files and what are they normally associated with? 
They are the standard input file, the standard output file and the standard error file. The first is usually associated with the keyboard, the second and third are usually associated with the terminal screen.

 

J2EE Interview Questions

Top most important J2EE interview questions and answers by Experts:

Here is a list of Top most important J2EE interview questions and answers by Experts.If you want to download J2EE interview questions pdf free ,you can register with RVH techguru. Our experts prepared these J2EE interview questions to accommodate freshers level to most experienced level technical interviews.

If you want to become an expert in J2EE ,Register for J2EE online training here.

 

1.What is J2EE?
J2EE is an environment for developing and deploying enterprise applications. The J2EE platform consists of a set of services, application programming interfaces (APIs), and protocols that provide the functionality for developing multitier, web-based applications.

2.What is the J2EE module? 
A J2EE module consists of one or more J2EE components for the same container type and one component deployment descriptor of that type.

3.What are the components of J2EE application? 
A J2EE component is a self-contained functional software unit that is assembled into a J2EE application with its related classes and files and communicates with other components. The J2EE specification defines the following J2EE components: 
   Application clients and applets are client components. 
   Java Servlet and JavaServer PagesTM (JSPTM) technology components are web components.
   Enterprise JavaBeansTM (EJBTM) components (enterprise beans) are business components.
   Resource adapter components provided by EIS and tool vendors.

4.What are the four types of J2EE modules? 
1. Application client module
2. Web module 
3. Enterprise JavaBeans module 
4. Resource adapter module

5.What does application client module contain? 
The application client module contains:
–class files, 
–an application client deployment descriptor.
Application client modules are packaged as JAR files with a .jar extension.

6.What does web module contain? 
The web module contains:
–JSP files,
–class files for servlets,
–GIF and HTML files, and 
–a Web deployment descriptor. 
Web modules are packaged as JAR files with a .war (Web ARchive) extension.

7.What are the differences between Ear, Jar and War files? Under what circumstances should we use each one?

There are no structural differences between the files; they are all archived using zip-jar compression. However, they are intended for different purposes.
–Jar files (files with a .jar extension) are intended to hold generic libraries of Java classes, resources, auxiliary files, etc.
–War files (files with a .war extension) are intended to contain complete Web applications. In this context, a Web application is defined as a single group of files, classes, resources, .jar files that can be packaged and accessed as one servlet context. 
–Ear files (files with a .ear extension) are intended to contain complete enterprise applications. In this context, an enterprise application is defined as a collection of .jar files, resources, classes, and multiple Web applications. 
Each type of file (.jar, .war, .ear) is processed uniquely by application servers, servlet containers, EJB containers, etc.

8.What is the difference between Session bean and Entity bean ? 
The Session bean and Entity bean are two main parts of EJB container. 
Session Bean
–represents a workflow on behalf of a client
–one-to-one logical mapping to a client.
–created and destroyed by a client 
–not permanent objects
–lives its EJB container(generally) does not survive system shut down
–two types: stateless and stateful beans
Entity Bean
–represents persistent data and behavior of this data
–can be shared among multiple clients 
–persists across multiple invocations 
–findable permanent objects
–outlives its EJB container, survives system shutdown 
–two types: container managed persistence(CMP) and bean managed persistence(BMP)

9.What is “applet”  ?
A J2EE component that typically executes in a Web browser but can execute in a variety of other applications or devices that support the applet programming model.

10.What is “applet container”  ?
A container that includes support for the applet programming model.

11.What is “application assembler” ?
A person who combines J2EE components and modules into deployable application units.

12.What is “application client” ?
A first-tier J2EE client component that executes in its own Java virtual machine. Application clients have access to some J2EE platform APIs.

13.What is “application client container” ?
A container that supports application client components.

14.What is “application client module” ?
A software unit that consists of one or more classes and an application client deployment descriptor.

15.What is “application component provider” ?
A vendor that provides the Java classes that implement components’ methods, JSP page definitions, and any required deployment descriptors.

16.What is “application configuration resource file” ?
An XML file used to configure resources for a Java Server Faces application, to define navigation rules for the application, and to register converters, Validator, listeners, renders, and components with the application.

17.What is “archiving” ?
The process of saving the state of an object and restoring it.

18.What is “asant” ?
A Java-based build tool that can be extended using Java classes. The configuration files are XML-based, calling out a target tree where various tasks get executed.

19.What is “attribute”?
A qualifier on an XML tag that provides additional information.

20.What is authentication ? 
The process that verifies the identity of a user, device, or other entity in a computer system, usually as a prerequisite to allowing access to resources in a system. The Java servlet specification requires three types of authentication-basic, form-based, and mutual-and supports digest authentication.

21.What is authorization ? 
The process by which access to a method or resource is determined. Authorization depends on the determination of whether the principal associated with a request through authentication is in a given security role. A security role is a logical grouping of users defined by the person who assembles the application. A deployer maps security roles to security identities. Security identities may be principals or groups in the operational environment.

22.What is authorization constraint ?
An authorization rule that determines who is permitted to access a Web resource collection.

23.What is B2B ?
B2B stands for Business-to-business.

24.What is backing bean ?
A JavaBeans component that corresponds to a JSP page that includes JavaServer Faces components. The backing bean defines properties for the components on the page and methods that perform processing for the component. This processing includes event handling, validation, and processing associated with navigation.

25.What is basic authentication ?
An authentication mechanism in which a Web server authenticates an entity via a user name and password obtained using the Web application’s built-in authentication mechanism.

26.What is bean-managed persistence ?
The mechanism whereby data transfer between an entity bean’s variables and a resource manager is managed by the entity bean.

27.What is bean-managed transaction ?
A transaction whose boundaries are defined by an enterprise bean.

28.What is binding (XML) ?
Generating the code needed to process a well-defined portion of XML data.

29.What is binding (JavaServer Faces technology) ?
Wiring UI components to back-end data sources such as backing bean properties.

30.What is build file ?
The XML file that contains one or more asant targets. A target is a set of tasks you want to be executed. When starting asant, you can select which targets you want to have executed. When no target is given, the project’s default target is executed.

31.What is business logic ?
The code that implements the functionality of an application. In the Enterprise JavaBeans architecture, this logic is implemented by the methods of an enterprise bean.

32.What is business method ?
A method of an enterprise bean that implements the business logic or rules of an application.

33.What is callback methods ?
Component methods called by the container to notify the component of important events in its life cycle.

34.What is caller ?
Same as caller principal.

35.What is caller principal ?
The principal that identifies the invoker of the enterprise bean method.

36.What is cascade delete ?
A deletion that triggers another deletion. A cascade delete can be specified for an entity bean that has container-managed persistence.

37.What is CDATA ?
A predefined XML tag for character data that means “don’t interpret these characters,” as opposed to parsed character data (PCDATA), in which the normal rules of XML syntax apply. CDATA sections are typically used to show examples of XML syntax.

38.What is certificate authority ?
A trusted organization that issues public key certificates and provides identification to the bearer.

39.What is client-certificate authentication ?
An authentication mechanism that uses HTTP over SSL, in which the server and, optionally, the client authenticate each other with a public key certificate that conforms to a standard that is defined by X.509 Public Key Infrastructure.

40.What is comment ?
In an XML document, text that is ignored unless the parser is specifically told to recognize it.

41.What is commit ?
The point in a transaction when all updates to any resources involved in the transaction are made permanent.

42.What is component contract ?
The contract between a J2EE component and its container. The contract includes life-cycle management of the component, a context interface that the instance uses to obtain various information and services from its container, and a list of services that every container must provide for its components.

43.What is component-managed sign-on ?
A mechanism whereby security information needed for signing on to a resource is provided by an application component.

44.What is connector ?
A standard extension mechanism for containers that provides connectivity to enterprise information systems. A connector is specific to an enterprise information system and consists of a resource adapter and application development tools for enterprise information system connectivity. The resource adapter is plugged in to a container through its support for system-level contracts defined in the Connector architecture.

45.What is container-managed persistence ?
The mechanism whereby data transfer between an entity bean’s variables and a resource manager is managed by the entity bean’s container.

46.What is container-managed sign-on ?
The mechanism whereby security information needed for signing on to a resource is supplied by the container.

47.What is container-managed transaction ?
A transaction whose boundaries are defined by an EJB container. An entity bean must use container-managed transactions.

48.What is content ?
In an XML document, the part that occurs after the prolog, including the root element and everything it contains.

49.What is context attribute ?
An object bound into the context associated with a servlet.

50.What is context root ?
A name that gets mapped to the document root of a Web application.

51.What is conversational state ?
The field values of a session bean plus the transitive closure of the objects reachable from the bean’s fields. The transitive closure of a bean is defined in terms of the serialization protocol for the Java programming language, that is, the fields that would be stored by serializing the bean instance.

52.What is CORBA ?
Common Object Request Broker Architecture. A language-independent distributed object model specified by the OMG.

53.What is create method ?
A method defined in the Interview Questions – Home interface and invoked by a client to create an enterprise bean.

54.What is credentials ?
The information describing the security attributes of a principal.

55.What is CSS ?
Cascading style sheet. A stylesheet used with HTML and XML documents to add a style to all elements marked with a particular tag, for the direction of browsers or other presentation mechanisms.

56.What is CTS ?
Compatibility test suite. A suite of compatibility tests for verifying that a J2EE product complies with the J2EE platform specification.

57.What is data ?
The contents of an element in an XML stream, generally used when the element does not contain any subelements. When it does, the term content is generally used. When the only text in an XML structure is contained in simple elements and when elements that have subelements have little or no data mixed in, then that structure is often thought of as XML data, as opposed to an XML document.

58.What is DDP ?
Document-driven programming. The use of XML to define applications.

59.What is declaration ?
The very first thing in an XML document, which declares it as XML. The minimal declaration is . The declaration is part of the document prolog.

60.What is declarative security ?
Mechanisms used in an application that are expressed in a declarative syntax in a deployment descriptor.

61.What is delegation ?
An act whereby one principal authorizes another principal to use its identity or privileges with some restrictions.

62.What is deployer ?
A person who installs J2EE modules and applications into an operational environment.

63.What is deployment ?
The process whereby software is installed into an operational environment.

64.What is deployment descriptor ?
An XML file provided with each module and J2EE application that describes how they should be deployed. The deployment descriptor directs a deployment tool to deploy a module or application with specific container options and describes specific configuration requirements that a deployer must resolve.

65.What is destination ?
A JMS administered object that encapsulates the identity of a JMS queue or topic. See point-to-point messaging system, publish/subscribe messaging system.

66.What is digest authentication ?
An authentication mechanism in which a Web application authenticates itself to a Web server by sending the server a message digest along with its HTTP request message. The digest is computed by employing a one-way hash algorithm to a concatenation of the HTTP request message and the client’s password. The digest is typically much smaller than the HTTP request and doesn’t contain the password. 

67.What is distributed application ?
An application made up of distinct components running in separate runtime environments, usually on different platforms connected via a network. Typical distributed applications are two-tier (client-server), three-tier (client-middleware-server), and multitier (client-multiple middleware-multiple servers).

68.What is document ?
In general, an XML structure in which one or more elements contains text intermixed with subelements.

69.What is Document Object Model ?
An API for accessing and manipulating XML documents as tree structures. DOM provides platform-neutral, language-neutral interfaces that enables programs and scripts to dynamically access and modify content and structure in XML documents. 

70.What is document root ?
The top-level directory of a WAR. The document root is where JSP pages, client-side classes and archives, and static Web resources are stored.

71.What is DTD ?
Document type definition. An optional part of the XML document prolog, as specified by the XML standard. The DTD specifies constraints on the valid tags and tag sequences that can be in the document. The DTD has a number of shortcomings, however, and this has led to various schema proposals. For example, the DTD entry says that the XML element called username contains parsed character data-that is, text alone, with no other structural elements under it. The DTD includes both the local subset, defined in the current file, and the external subset, which consists of the definitions contained in external DTD files that are referenced in the local subset using a parameter entity.

72.What is durable subscription ?
In a JMS publish/subscribe messaging system, a subscription that continues to exist whether or not there is a current active subscriber object. If there is no active subscriber, the JMS provider retains the subscription’s messages until they are received by the subscription or until they expire.

73.What is EAR file ?
Enterprise Archive file. A JAR archive that contains a J2EE application.

74.What is ebXML ?
Electronic Business XML. A group of specifications designed to enable enterprises to conduct business through the exchange of XML-based messages. It is sponsored by OASIS and the United Nations Centre for the Facilitation of Procedures and Practices in Administration, Commerce and Transport (U.N./CEFACT).

75. What is EJB ?
Enterprise JavaBeans.

76.What is EJB container ?
A container that implements the EJB component contract of the J2EE architecture. This contract specifies a runtime environment for enterprise beans that includes security, concurrency, life-cycle management, transactions, deployment, naming, and other services. An EJB container is provided by an EJB or J2EE server.

77.What is EJB container provider ?
A vendor that supplies an EJB container.

78.What is EJB context ?
A vendor that supplies an EJB container. An object that allows an enterprise bean to invoke services provided by the container and to obtain the information about the caller of a client-invoked method

79.What is EJB Home object ?
An object that provides the life-cycle operations (create, remove, find) for an enterprise bean. The class for the EJB Home object is generated by the container’s deployment tools. The EJB Home object implements the enterprise bean’s Home interface. The client references an EJB Home object to perform life-cycle operations on an EJB object. The client uses JNDI to locate an EJB Home object.

80.What is EJB JAR file ?
A JAR archive that contains an EJB module.

81.What is EJB module ?
A deployable unit that consists of one or more enterprise beans and an EJB deployment descriptor.

82.What is EJB object ?
An object whose class implements the enterprise bean’s remote interface. A client never references an enterprise bean instance directly; a client always references an EJB object. The class of an EJB object is generated by a container’s deployment tools.

83.What is EJB server ?
Software that provides services to an EJB container. For example, an EJB container typically relies on a transaction manager that is part of the EJB server to perform the two-phase commit across all the participating resource managers. The J2EE architecture assumes that an EJB container is hosted by an EJB server from the same vendor, so it does not specify the contract between these two entities. An EJB server can host one or more EJB containers.

84.What is EJB server provider ?
A vendor that supplies an EJB server.

85.What is element ?
A unit of XML data, delimited by tags. An XML element can enclose other elements.

86.What is empty tag ?
A tag that does not enclose any content.

87.What is enterprise bean ?
A J2EE component that implements a business task or business entity and is hosted by an EJB container; either an entity bean, a session bean, or a message-driven bean.

88.What is enterprise bean provider ?
An application developer who produces enterprise bean classes, remote and Interview Questions – Home interfaces, and deployment descriptor files, and packages them in an EJB JAR file.

89.What is enterprise information system ?
The applications that constitute an enterprise’s existing system for handling companywide information. These applications provide an information infrastructure for an enterprise. An enterprise information system offers a well-defined set of services to its clients. These services are exposed to clients as local or remote interfaces or both. Examples of enterprise information systems include enterprise resource planning systems, mainframe transaction processing systems, and legacy database systems.

90.What is enterprise information system resource ?
An entity that provides enterprise information system-specific functionality to its clients. Examples are a record or set of records in a database system, a business object in an enterprise resource planning system, and a transaction program in a transaction processing system.

91.What is Enterprise JavaBeans (EJB) ?
A component architecture for the development and deployment of object-oriented, distributed, enterprise-level applications. Applications written using the Enterprise JavaBeans architecture are scalable, transactional, and secure.

92.What is Enterprise JavaBeans Query Language (EJB QL) ?
Defines the queries for the finder and select methods of an entity bean having container-managed persistence. A subset of SQL92, EJB QL has extensions that allow navigation over the relationships defined in an entity bean’s abstract schema.

93.What is an entity ?
A distinct, individual item that can be included in an XML document by referencing it. Such an entity reference can name an entity as small as a character (for example, <, which references the less-than symbol or left angle bracket, <). An entity reference can also reference an entire document, an external entity, or a collection of DTD definitions.

94.What is entity bean ?
An enterprise bean that represents persistent data maintained in a database. An entity bean can manage its own persistence or can delegate this function to its container. An entity bean is identified by a primary key. If the container in which an entity bean is hosted crashes, the entity bean, its primary key, and any remote references survive the crash.

95.What is entity reference ?
A reference to an entity that is substituted for the reference when the XML document is parsed. It can reference a predefined entity such as < or reference one that is defined in the DTD. In the XML data, the reference could be to an entity that is defined in the local subset of the DTD or to an external XML file (an external entity). The DTD can also carve out a segment of DTD specifications and give it a name so that it can be reused (included) at multiple points in the DTD by defining a parameter entity.

96.What is error ?
A SAX parsing error is generally a validation error; in other words, it occurs when an XML document is not valid, although it can also occur if the declaration specifies an XML version that the parser cannot handle. See also fatal error, warning. 

97.What is Extensible Markup Language ?
XML.

98.What is external entity ?
An entity that exists as an external XML file, which is included in the XML document using an entity reference.

99.What is external subset ?
That part of a DTD that is defined by references to external DTD files.

100.What is fatal error ?
A fatal error occurs in the SAX parser when a document is not well formed or otherwise cannot be processed. See also error, warning.

101.What is filter ?
An object that can transform the header or content (or both) of a request or response. Filters differ from Web components in that they usually do not themselves create responses but rather modify or adapt the requests for a resource, and modify or adapt responses from a resource. A filter should not have any dependencies on a Web resource for which it is acting as a filter so that it can be composable with more than one type of Web resource.

102.What is filter chain ?
A concatenation of XSLT transformations in which the output of one transformation becomes the input of the next.

103.What is finder method ?
A method defined in the Interview Questions – Home interface and invoked by a client to locate an entity bean.

104.What is form-based authentication ?
An authentication mechanism in which a Web container provides an application-specific form for logging in. This form of authentication uses Base64 encoding and can expose user names and passwords

105.What is general entity ?
An entity that is referenced as part of an XML document’s content, as distinct from a parameter entity, which is referenced in the DTD. A general entity can be a parsed entity or an unparsed entity.

106.What is group ?
An authenticated set of users classified by common traits such as job title or customer profile. Groups are also associated with a set of roles, and every user that is a member of a group inherits all the roles assigned to that group.

107.What is handle ?
An object that identifies an enterprise bean. A client can serialize the handle and then later deserialize it to obtain a reference to the enterprise bean.

108.What is Interview Questions – Home handle ?
An object that can be used to obtain a reference to the Interview Questions – Home interface. A Interview Questions – Home handle can be serialized and written to stable storage and de-serialized to obtain the reference.

109.What is Interview Questions – Home interface ?
One of two interfaces for an enterprise bean. The Interview Questions – Home interface defines zero or more methods for managing an enterprise bean. The Interview Questions – Home interface of a session bean defines create and remove methods, whereas the Interview Questions – Home interface of an entity bean defines create, finder, and remove methods.

110.What is HTML ?
Hypertext Markup Language. A markup language for hypertext documents on the Internet. HTML enables the embedding of images, sounds, video streams, form fields, references to other objects with URLs, and basic text formatting.

111.What is HTTP ?
Hypertext Transfer Protocol. The Internet protocol used to retrieve hypertext objects from remote hosts. HTTP messages consist of requests from client to server and responses from server to client.

112.What is HTTPS ?
HTTP layered over the SSL protocol.

113.What is IDL ?
Interface Definition Language. A language used to define interfaces to remote CORBA objects. The interfaces are independent of operating systems and programming languages.

114.What is IIOP ?
Internet Inter-ORB Protocol. A protocol used for communication between CORBA object request brokers.

115.What is impersonation ?
An act whereby one entity assumes the identity and privileges of another entity without restrictions and without any indication visible to the recipients of the impersonator’s calls that delegation has taken place. Impersonation is a case of simple delegation.

116.What is initialization parameter ?
A parameter that initializes the context associated with a servlet.

117.What is ISO 3166 ?
The international standard for country codes maintained by the International Organization for Standardization (ISO).

118.What is ISV ?
Independent software vendor.

119.What is J2EE ?
Java 2 Platform, Enterprise Edition.

120.What is J2EE application ?
Any deployable unit of J2EE functionality. This can be a single J2EE module or a group of modules packaged into an EAR file along with a J2EE application deployment descriptor. J2EE applications are typically engineered to be distributed across multiple computing tiers.

121.What is J2EE component ?
A self-contained functional software unit supported by a container and configurable at deployment time. The J2EE specification defines the following J2EE components: Application clients and applets are components that run on the client. Java servlet and JavaServer Pages (JSP) technology components are Web components that run on the server. Enterprise JavaBeans (EJB) components (enterprise beans) are business components that run on the server. J2EE components are written in the Java programming language and are compiled in the same way as any program in the language. The difference between J2EE components and “standard” Java classes is that J2EE components are assembled into a J2EE application, verified to be well formed and in compliance with the J2EE specification, and deployed to production, where they are run and managed by the J2EE server or client container.

122.What is J2EE module ?
A software unit that consists of one or more J2EE components of the same container type and one deployment descriptor of that type. There are four types of modules: EJB, Web, application client, and resource adapter. Modules can be deployed as stand-alone units or can be assembled into a J2EE application.

123.What is J2EE product ?
An implementation that conforms to the J2EE platform specification.

124.What is J2EE product provider ?
A vendor that supplies a J2EE product.

125.What is J2EE server ?
The runtime portion of a J2EE product. A J2EE server provides EJB or Web containers or both.

126.What is J2ME ?
Abbreviate of Java 2 Platform, Micro Edition.

127.What is J2SE ?
Abbreviate of Java 2 Platform, Standard Edition.

128.What is JAR ?
Java archive. A platform-independent file format that permits many files to be aggregated into one file.

129.What is Java 2 Platform, Enterprise Edition (J2EE) ?
An environment for developing and deploying enterprise applications. The J2EE platform consists of a set of services, application programming interfaces (APIs), and protocols that provide the functionality for developing multitiered, Web-based applications.

130.What is Java 2 Platform, Micro Edition (J2ME) ?
A highly optimized Java runtime environment targeting a wide range of consumer products, including pagers, cellular phones, screen phones, digital set-top boxes, and car navigation systems.

131.What is Java 2 Platform, Standard Edition (J2SE) ?
The core Java technology platform.

132.What is Java API for XML Processing (JAXP) ?
An API for processing XML documents. JAXP leverages the parser standards SAX and DOM so that you can choose to parse your data as a stream of events or to build a tree-structured representation of it. JAXP supports the XSLT standard, giving you control over the presentation of the data and enabling you to convert the data to other XML documents or to other formats, such as HTML. JAXP provides namespace support, allowing you to work with schema that might otherwise have naming conflicts.

133.What is Java API for XML Registries (JAXR) ?
An API for accessing various kinds of XML registries.

134.What is Java API for XML-based RPC (JAX-RPC) ?
An API for building Web services and clients that use remote procedure calls and XML.  

135.What is Java IDL ?
A technology that provides CORBA interoperability and connectivity capabilities for the J2EE platform. These capabilities enable J2EE applications to invoke operations on remote network services using the Object Management Group IDL and IIOP.

136.What is Java Message Service (JMS) ?
An API for invoking operations on enterprise messaging systems.

137.What is Java Naming and Directory Interface (JNDI) ?
An API that provides naming and directory functionality.

138.What is Java Secure Socket Extension (JSSE) ?
A set of packages that enable secure Internet communications.

139.What is Java Transaction API (JTA) ?
An API that allows applications and J2EE servers to access transactions.

140.What is Java Transaction Service (JTS) ?
Specifies the implementation of a transaction manager that supports JTA and implements the Java mapping of the Object Management Group Object Transaction Service 1.1 specification at the level below the API.

141.What is JavaBeans component ?
A Java class that can be manipulated by tools and composed into applications. A JavaBeans component must adhere to certain property and event interface conventions. 

142.What is JavaMail ?
An API for sending and receiving email.

143.What is JavaServer Faces Technology ?
A framework for building server-side user interfaces for Web applications written in the Java programming language.

144.What is JavaServer Faces conversion model ?
A mechanism for converting between string-based markup generated by JavaServer Faces UI components and server-side Java objects.

145.What is JavaServer Faces event and listener model ?
A mechanism for determining how events emitted by JavaServer Faces UI components are handled. This model is based on the JavaBeans component event and listener model.

146.What is JavaServer Faces expression language ?
A simple expression language used by a JavaServer Faces UI component tag attributes to bind the associated component to a bean property or to bind the associated component’s value to a method or an external data source, such as a bean property. Unlike JSP EL expressions, JavaServer Faces EL expressions are evaluated by the JavaServer Faces implementation rather than by the Web container.

147.What is JavaServer Faces navigation model ?
A mechanism for defining the sequence in which pages in a JavaServer Faces application are displayed.

148.What is JavaServer Faces UI component ?
A user interface control that outputs data to a client or allows a user to input data to a JavaServer Faces application.

149.What is JavaServer Faces UI component class ?
A JavaServer Faces class that defines the behavior and properties of a JavaServer Faces UI component.

150.What is JavaServer Faces validation model ?
A mechanism for validating the data a user inputs to a JavaServer Faces UI component.

151.What is JavaServer Pages (JSP) ?
An extensible Web technology that uses static data, JSP elements, and server-side Java objects to generate dynamic content for a client. Typically the static data is HTML or XML elements, and in many cases the client is a Web browser.

152.What is JavaServer Pages Standard Tag Library (JSTL) ?
A tag library that encapsulates core functionality common to many JSP applications. JSTL has support for common, structural tasks such as iteration and conditionals, tags for manipulating XML documents, internationalization and locale-specific formatting tags, SQL tags, and functions.

153.What is JAXR client ?
A client program that uses the JAXR API to access a business registry via a JAXR provider.

154.What is JAXR provider ?
An implementation of the JAXR API that provides access to a specific registry provider or to a class of registry providers that are based on a common specification.

155.What is JDBC ?
An JDBC for database-independent connectivity between the J2EE platform and a wide range of data sources.

156.What is JMS ?
Java Message Service.

157.What is JMS administered object ?
A preconfigured JMS object (a resource manager connection factory or a destination) created by an administrator for the use of JMS clients and placed in a JNDI namespace.

158.What is JMS application ?
One or more JMS clients that exchange messages.

159.What is JMS client ?
A Java language program that sends or receives messages.

160.What is JMS provider ?
A messaging system that implements the Java Message Service as well as other administrative and control functionality needed in a full-featured messaging product.

161.What is JMS session ?
A single-threaded context for sending and receiving JMS messages. A JMS session can be nontransacted, locally transacted, or participating in a distributed transaction.

162.What is JNDI ?
Abbreviate of Java Naming and Directory Interface.

163.What is JSP ?
Abbreviate of JavaServer Pages.

164.What is JSP action ?
A JSP element that can act on implicit objects and other server-side objects or can define new scripting variables. Actions follow the XML syntax for elements, with a start tag, a body, and an end tag; if the body is empty it can also use the empty tag syntax. The tag must use a prefix. There are standard and custom actions.

165.What is JSP container ?
A container that provides the same services as a servlet container and an engine that interprets and processes JSP pages into a servlet.

166.What is JSP container, distributed ?
A JSP container that can run a Web application that is tagged as distributable and is spread across multiple Java virtual machines that might be running on different hosts.

167.What is JSP custom action ?
A user-defined action described in a portable manner by a tag library descriptor and imported into a JSP page by a taglib directive. Custom actions are used to encapsulate recurring tasks in writing JSP pages.

168.What is JSP custom tag ?
A tag that references a JSP custom action.

169.What is JSP declaration ?
A JSP scripting element that declares methods, variables, or both in a JSP page.

170.What is JSP directive ?
A JSP element that gives an instruction to the JSP container and is interpreted at translation time.

171.What is JSP document ?
A JSP page written in XML syntax and subject to the constraints of XML documents. 

172.What is JSP element ?
A portion of a JSP page that is recognized by a JSP translator. An element can be a directive, an action, or a scripting element.

173.What is JSP expression ?
A scripting element that contains a valid scripting language expression that is evaluated, converted to a String, and placed into the implicit out object.

174.What is JSP expression language ?
A language used to write expressions that access the properties of JavaBeans components. EL expressions can be used in static text and in any standard or custom tag attribute that can accept an expression.

175.What is JSP page ?
A text-based document containing static text and JSP elements that describes how to process a request to create a response. A JSP page is translated into and handles requests as a servlet.

176.What is JSP scripting element ?
A JSP declaration, scriptlet, or expression whose syntax is defined by the JSP specification and whose content is written according to the scripting language used in the JSP page. The JSP specification describes the syntax and semantics for the case where the language page attribute is “java”.

177.What is JSP scriptlet ?
A JSP scripting element containing any code fragment that is valid in the scripting language used in the JSP page. The JSP specification describes what is a valid scriptlet for the case where the language page attribute is “java”.

178.What is JSP standard action ?
An action that is defined in the JSP specification and is always available to a JSP page.

179.What is JSP tag file ?
A source file containing a reusable fragment of JSP code that is translated into a tag handler when a JSP page is translated into a servlet.

180.What is JSP tag handler ?
A Java programming language object that implements the behavior of a custom tag.

181.What is JSP tag library ?
A collection of custom tags described via a tag library descriptor and Java classes. 

182.What is JSTL ?
Abbreviate of JavaServer Pages Standard Tag Library.

183.What is JTA ?
Abbreviate of Java Transaction API.

184.What is JTS ?
Abbreviate of Java Transaction Service.

185.What is keystore ?
A file containing the keys and certificates used for authentication

186.What is life cycle (J2EE component) ?
The framework events of a J2EE component’s existence. Each type of component has defining events that mark its transition into states in which it has varying availability for use. For example, a servlet is created and has its init method called by its container before invocation of its service method by clients or other servlets that require its functionality. After the call of its init method, it has the data and readiness for its intended use. The servlet’s destroy method is called by its container before the ending of its existence so that processing associated with winding up can be done and resources can be released. The init and destroy methods in this example are callback methods. Similar considerations apply to the life cycle of all J2EE component types: enterprise beans, Web components (servlets or JSP pages), applets, and application clients.

187.What is life cycle (JavaServer Faces) ?
A set of phases during which a request for a page is received, a UI component tree representing the page is processed, and a response is produced. During the phases of the life cycle: The local data of the components is updated with the values contained in the request parameters. Events generated by the components are processed. Validators and converters registered on the components are processed. The components’ local data is updated to back-end objects. The response is rendered to the client while the component state of the response is saved on the server for future requests.

188.What is local subset ?
That part of the DTD that is defined within the current XML file.

189.What is managed bean creation facility ?
A mechanism for defining the characteristics of JavaBeans components used in a JavaServer Faces application.

190.What is message ?
In the Java Message Service, an asynchronous request, report, or event that is created, sent, and consumed by an enterprise application and not by a human. It contains vital information needed to coordinate enterprise applications, in the form of precisely formatted data that describes specific business actions.

191.What is message consumer ?
An object created by a JMS session that is used for receiving messages sent to a destination.

192.What is message-driven bean ?
An enterprise bean that is an asynchronous message consumer. A message-driven bean has no state for a specific client, but its instance variables can contain state across the handling of client messages, including an open database connection and an object reference to an EJB object. A client accesses a message-driven bean by sending messages to the destination for which the bean is a message listener.

193.What is message producer ?
An object created by a JMS session that is used for sending messages to a destination.

194.What is mixed-content model ?
A DTD specification that defines an element as containing a mixture of text and one more other elements. The specification must start with #PCDATA, followed by diverse elements, and must end with the “zero-or-more” asterisk symbol (*).

195.What is method-binding expression ?
A Java Server Faces EL expression that refers to a method of a backing bean. This method performs either event handling, validation, or navigation processing for the UI component whose tag uses the method-binding expression.

196.What is method permission ?
An authorization rule that determines who is permitted to execute one or more enterprise bean methods.

197.What is mutual authentication ?
An authentication mechanism employed by two parties for the purpose of proving each other’s identity to one another.

198.What is namespace ?
A standard that lets you specify a unique label for the set of element names defined by a DTD. A document using that DTD can be included in any other document without having a conflict between element names. The elements defined in your DTD are then uniquely identified so that, for example, the parser can tell when an element should be interpreted according to your DTD rather than using the definition for an element in a different DTD.

199.What is naming context ?
A set of associations between unique, atomic, people-friendly identifiers and objects.

200.What is naming environment ?
A mechanism that allows a component to be customized without the need to access or change the component’s source code. A container implements the component’s naming environment and provides it to the component as a JNDI naming context. Each component names and accesses its environment entries using the java:comp/env JNDI context. The environment entries are declaratively specified in the component’s deployment descriptor.

201.What is normalization ?
The process of removing redundancy by modularizing, as with subroutines, and of removing superfluous differences by reducing them to a common denominator. For example, line endings from different systems are normalized by reducing them to a single new line, and multiple whitespace characters are normalized to one space.

202.What is North American Industry Classification System (NAICS) ?
A system for classifying business establishments based on the processes they use to produce goods or services.

203.What is notation ?
A mechanism for defining a data format for a non-XML document referenced as an unparsed entity. This is a holdover from SGML. A newer standard is to use MIME data types and namespaces to prevent naming conflicts.

204.What is OASIS ?
Organization for the Advancement of Structured Information Standards. A consortium that drives the development, convergence, and adoption of e-business standards.

205.What is OMG ?
Object Management Group. A consortium that produces and maintains computer industry specifications for interoperable enterprise applications.

206.What is one-way messaging ?
A method of transmitting messages without having to block until a response is received.

207.What is ORB ?
Object request broker. A library that enables CORBA objects to locate and communicate with one another.

208.What is OS principal ?
A principal native to the operating system on which the J2EE platform is executing.

209.What is OTS ?
Object Transaction Service. A definition of the interfaces that permit CORBA objects to participate in transactions

210.What is parameter entity ?
An entity that consists of DTD specifications, as distinct from a general entity. A parameter entity defined in the DTD can then be referenced at other points, thereby eliminating the need to recode the definition at each location it is used.

211.What is parsed entity ?
A general entity that contains XML and therefore is parsed when inserted into the XML document, as opposed to an unparsed entity.

212.What is parser ?
A module that reads in XML data from an input source and breaks it into chunks so that your program knows when it is working with a tag, an attribute, or element data. A nonvalidating parser ensures that the XML data is well formed but does not verify that it is valid. See also validating parser.

213.What is passivation ?
The process of transferring an enterprise bean from memory to secondary storage. See activation.

214.What is persistence ?
The protocol for transferring the state of an entity bean between its instance variables and an underlying database.

215.What is persistent field ?
A virtual field of an entity bean that has container-managed persistence; it is stored in a database.

216.What is POA ?
Portable Object Adapter. A CORBA standard for building server-side applications that are portable across heterogeneous ORBs.

217.What is point-to-point messaging system ?
A messaging system built on the concept of message queues. Each message is addressed to a specific queue; clients extract messages from the queues established to hold their messages.

218.What is primary key ?
An object that uniquely identifies an entity bean within a home.

219.What is principal ?
The identity assigned to a user as a result of authentication.

220.What is privilege ?
A security attribute that does not have the property of uniqueness and that can be shared by many principals.

221.What is processing instruction ?
Information contained in an XML structure that is intended to be interpreted by a specific application.

222.What is programmatic security ?
Security decisions that are made by security-aware applications. Programmatic security is useful when declarative security alone is not sufficient to express the security model of an application.

223.What is prolog ?
The part of an XML document that precedes the XML data. The prolog includes the declaration and an optional DTD.

224.What is public key certificate ?
Used in client-certificate authentication to enable the server, and optionally the client, to authenticate each other. The public key certificate is the digital equivalent of a passport. It is issued by a trusted organization, called a certificate authority, and provides identification for the bearer.

225.What is publish/subscribe messaging system ?
A messaging system in which clients address messages to a specific node in a content hierarchy, called a topic. Publishers and subscribers are generally anonymous and can dynamically publish or subscribe to the content hierarchy. The system takes care of distributing the messages arriving from a node’s multiple publishers to its multiple subscribers.

226.What is query string ?
A component of an HTTP request URL that contains a set of parameters and values that affect the handling of the request.

227.What is queue ?
A messaging system built on the concept of message queues. Each message is addressed to a specific queue; clients extract messages from the queues established to hold their messages.

228.What is RAR ?
Resource Adapter Archive. A JAR archive that contains a resource adapter module.

229.What is RDF ?
Resource Description Framework. A standard for defining the kind of data that an XML file contains. Such information can help ensure semantic integrity-for example-by helping to make sure that a date is treated as a date rather than simply as text.

230.What is RDF schema ?
A standard for specifying consistency rules that apply to the specifications contained in an RDF.

231.What is realm ?
See security policy domain. Also, a string, passed as part of an HTTP request during basic authentication, that defines a protection space. The protected resources on a server can be partitioned into a set of protection spaces, each with its own authentication scheme or authorization database or both. In the J2EE server authentication service, a realm is a complete database of roles, users, and groups that identify valid users of a Web application or a set of Web applications.

232.What is reentrant entity bean ?
An entity bean that can handle multiple simultaneous, interleaved, or nested invocations that will not interfere with each other.

233.What is reference ?
A reference to an entity that is substituted for the reference when the XML document is parsed. It can reference a predefined entity such as < or reference one that is defined in the DTD. In the XML data, the reference could be to an entity that is defined in the local subset of the DTD or to an external XML file (an external entity). The DTD can also carve out a segment of DTD specifications and give it a name so that it can be reused (included) at multiple points in the DTD by defining a parameter entity.

234.What is registry ?
An infrastructure that enables the building, deployment, and discovery of Web services. It is a neutral third party that facilitates dynamic and loosely coupled business-to-business (B2B) interactions.

235.What is registry provider ?
An implementation of a business registry that conforms to a specification for XML registries (for example, ebXML or UDDI).

236.What is relationship field ?
A virtual field of an entity bean having container-managed persistence; it identifies a related entity bean.

237.What is remote interface ?
One of two interfaces for an enterprise bean. The remote interface defines the business methods callable by a client.

238.What is remove method ?
Method defined in the Home interface and invoked by a client to destroy an enterprise bean.

239.What is render kit ?
A set of renderers that render output to a particular client. The JavaServer Faces implementation provides a standard HTML render kit, which is composed of renderers that can render HMTL markup.

240.What is renderer ?
A Java class that can render the output for a set of JavaServer Faces UI components.

241.What is resource adapter ?
A system-level software driver that is used by an EJB container or an application client to connect to an enterprise information system. A resource adapter typically is specific to an enterprise information system. It is available as a library and is used within the address space of the server or client using it. A resource adapter plugs in to a container. The application components deployed on the container then use the client API (exposed by the adapter) or tool-generated high-level abstractions to access the underlying enterprise information system. The resource adapter and EJB container collaborate to provide the underlying mechanisms-transactions, security, and connection pooling-for connectivity to the enterprise information system.

242.What is resource adapter module ?
A deployable unit that contains all Java interfaces, classes, and native libraries, implementing a resource adapter along with the resource adapter deployment descriptor.

243.What is resource manager ?
Provides access to a set of shared resources. A resource manager participates in transactions that are externally controlled and coordinated by a transaction manager. A resource manager typically is in a different address space or on a different machine from the clients that access it. Note: An enterprise information system is referred to as a resource manager when it is mentioned in the context of resource and transaction management.

244.What is resource manager connection ?
An object that represents a session with a resource manager.

245.What is resource manager connection factory ?
An object used for creating a resource manager connection.

246.What is RMI ?
Remote Method Invocation. A technology that allows an object running in one Java virtual machine to invoke methods on an object running in a different Java virtual machine.

247.What is RMI-IIOP ?
A version of RMI implemented to use the CORBA IIOP protocol. RMI over IIOP provides interoperability with CORBA objects implemented in any language if all the remote interfaces are originally defined as RMI interfaces.

248.What is role (development) ?
The function performed by a party in the development and deployment phases of an application developed using J2EE technology. The roles are application component provider, application assembler, deployer, J2EE product provider, EJB container provider, EJB server provider, Web container provider, Web server provider, tool provider, and system administrator.

249.What is role mapping ?
The process of associating the groups or principals (or both), recognized by the container with security roles specified in the deployment descriptor. Security roles must be mapped by the deployer before a component is installed in the server.

250.What is role (security) ?
An abstract logical grouping of users that is defined by the application assembler. When an application is deployed, the roles are mapped to security identities, such as principals or groups, in the operational environment. In the J2EE server authentication service, a role is an abstract name for permission to access a particular set of resources. A role can be compared to a key that can open a lock. Many people might have a copy of the key; the lock doesn’t care who you are, only that you have the right key.

251.What is rollback ?
The point in a transaction when all updates to any resources involved in the transaction are reversed.

252.What is root ?
The outermost element in an XML document. The element that contains all other elements.

253.What is SAX ?
Abbreviation of Simple API for XML.

254.What is Simple API for XML ?
An event-driven interface in which the parser invokes one of several methods supplied by the caller when a parsing event occurs. Events include recognizing an XML tag, finding an error, encountering a reference to an external entity, or processing a DTD specification.

255.What is schema ?
A database-inspired method for specifying constraints on XML documents using an XML-based language. Schemas address deficiencies in DTDs, such as the inability to put constraints on the kinds of data that can occur in a particular field. Because schemas are founded on XML, they are hierarchical. Thus it is easier to create an unambiguous specification, and it is possible to determine the scope over which a comment is meant to apply.

256.What is Secure Socket Layer (SSL) ?
A technology that allows Web browsers and Web servers to communicate over a secured connection.

257.What is security attributes ?
A set of properties associated with a principal. Security attributes can be associated with a principal by an authentication protocol or by a J2EE product provider or both. 

258.What is security constraint ?
A declarative way to annotate the intended protection of Web content. A security constraint consists of a Web resource collection, an authorization constraint, and a user data constraint.

259.What is security context ?
An object that encapsulates the shared state information regarding security between two entities.

260.What is security permission ?
A mechanism defined by J2SE, and used by the J2EE platform to express the programming restrictions imposed on application component developers.

261.What is security permission set ?
The minimum set of security permissions that a J2EE product provider must provide for the execution of each component type.

262.What is security policy domain ?
A scope over which security policies are defined and enforced by a security administrator. A security policy domain has a collection of users (or principals), uses a well-defined authentication protocol or protocols for authenticating users (or principals), and may have groups to simplify setting of security policies.

263.What is security role ?
An abstract logical grouping of users that is defined by the application assembler. When an application is deployed, the roles are mapped to security identities, such as principals or groups, in the operational environment. In the J2EE server authentication service, a role is an abstract name for permission to access a particular set of resources. A role can be compared to a key that can open a lock. Many people might have a copy of the key; the lock doesn’t care who you are, only that you have the right key.

264.What is security technology domain ?
A scope over which the same security mechanism is used to enforce a security policy. Multiple security policy domains can exist within a single technology domain.

265.What is security view ?
The set of security roles defined by the application assembler.

266.What is server certificate ?
Used with the HTTPS protocol to authenticate Web applications. The certificate can be self-signed or approved by a certificate authority (CA). The HTTPS service of the Sun Java System Application Server Platform Edition 8 will not run unless a server certificate has been installed.

267.What is server principal ?
The OS principal that the server is executing as.

268.What is service element ?
A representation of the combination of one or more Connector components that share a single engine component for processing incoming requests.

269.What is service endpoint interface ?
A Java interface that declares the methods that a client can invoke on a Web service.

270.What is servlet ?
A Java program that extends the functionality of a Web server, generating dynamic content and interacting with Web applications using a request-response paradigm.

271.What is servlet container ?
A container that provides the network services over which requests and responses are sent, decodes requests, and formats responses. All servlet containers must support HTTP as a protocol for requests and responses but can also support additional request-response protocols, such as HTTPS.

272.What is servlet container, distributed ?
A servlet container that can run a Web application that is tagged as distributable and that executes across multiple Java virtual machines running on the same host or on different hosts.

273.What is servlet context ?
An object that contains a servlet’s view of the Web application within which the servlet is running. Using the context, a servlet can log events, obtain URL references to resources, and set and store attributes that other servlets in the context can use. 

274.What is servlet mapping ?
Defines an association between a URL pattern and a servlet. The mapping is used to map requests to servlets.

275.What is session ?
An object used by a servlet to track a user’s interaction with a Web application across multiple HTTP requests.

276.What is session bean ?
An enterprise bean that is created by a client and that usually exists only for the duration of a single client-server session. A session bean performs operations, such as calculations or database access, for the client. Although a session bean can be transactional, it is not recoverable should a system crash occur. Session bean objects either can be stateless or can maintain conversational state across methods and transactions. If a session bean maintains state, then the EJB container manages this state if the object must be removed from memory. However, the session bean object itself must manage its own persistent data.

277.What is SGML ?
Standard Generalized Markup Language. The parent of both HTML and XML. Although HTML shares SGML’s propensity for embedding presentation information in the markup, XML is a standard that allows information content to be totally separated from the mechanisms for rendering that content.

278.What is SOAP ?
Simple Object Access Protocol. A lightweight protocol intended for exchanging structured information in a decentralized, distributed environment. It defines, using XML technologies, an extensible messaging framework containing a message construct that can be exchanged over a variety of underlying protocols.

279.What is SOAP with Attachments API for Java (SAAJ) ?
The basic package for SOAP messaging, SAAJ contains the API for creating and populating a SOAP message.

280.What is SQL ?
Structured Query Language. The standardized relational database language for defining database objects and manipulating data.

281.What is SQL/J ?
A set of standards that includes specifications for embedding SQL statements in methods in the Java programming language and specifications for calling Java static methods as SQL stored procedures and user-defined functions. An SQL checker can detect errors in static SQL statements at program development time, rather than at execution time as with a JDBC driver.

282.What is SSL ?
Secure Socket Layer. A security protocol that provides privacy over the Internet. The protocol allows client-server applications to communicate in a way that cannot be eavesdropped upon or tampered with. Servers are always authenticated, and clients are optionally authenticated.

283.What is stateful session bean ?
A session bean with a conversational state.

284.What is stateless session bean ?
A session bean with no conversational state. All instances of a stateless session bean are identical.

285.What is system administrator ?
The person responsible for configuring and administering the enterprise’s computers, networks, and software systems.

286.What is tag ?
In XML documents, a piece of text that describes a unit of data or an element. The tag is distinguishable as markup, as opposed to data, because it is surrounded by angle brackets (< and >). To treat such markup syntax as data, you use an entity reference or a CDATA section.

287.What is template ?
A set of formatting instructions that apply to the nodes selected by an XPath expression.

288.What is tool provider ?
An organization or software vendor that provides tools used for the development, packaging, and deployment of J2EE applications.

289.What is transaction attribute ?
A value specified in an enterprise bean’s deployment descriptor that is used by the EJB container to control the transaction scope when the enterprise bean’s methods are invoked. A transaction attribute can have the following values: Required, RequiresNew, Supports, NotSupported, Mandatory, or Never.

290.What is transaction ?
An atomic unit of work that modifies data. A transaction encloses one or more program statements, all of which either complete or roll back. Transactions enable multiple users to access the same data concurrently.

291.What is transaction isolation level ?
What is transaction isolation level The degree to which the intermediate state of the data being modified by a transaction is visible to other concurrent transactions and data being modified by other transactions is visible to it.

292.What is transaction manager ?
Provides the services and management functions required to support transaction demarcation, transactional resource management, synchronization, and transaction context propagation.

293.What is Unicode ?
A standard defined by the Unicode Consortium that uses a 16-bit code page that maps digits to characters in languages around the world. Because 16 bits covers 32,768 codes, Unicode is large enough to include all the world’s languages, with the exception of ideographic languages that have a different character for every concept, such as Chinese.

294.What is Universal Description, Discovery and Integration (UDDI) project ?
An industry initiative to create a platform-independent, open framework for describing services, discovering businesses, and integrating business services using the Internet, as well as a registry. It is being developed by a vendor consortium.

295.What is Universal Standard Products and Services Classification (UNSPSC) ?
A schema that classifies and identifies commodities. It is used in sell-side and buy-side catalogs and as a standardized account code in analyzing expenditure.

296.What is unparsed entity ?
A general entity that contains something other than XML. By its nature, an unparsed entity contains binary data.

297.What is URI ?
Uniform resource identifier. A globally unique identifier for an abstract or physical resource. A URL is a kind of URI that specifies the retrieval protocol (http or https for Web applications) and physical location of a resource (host name and host-relative path). A URN is another type of URI.

298.What is URL ?
Uniform resource locator. A standard for writing a textual reference to an arbitrary piece of data in the World Wide Web. A URL looks like this: protocol://host/local info where protocol specifies a protocol for fetching the object (such as http or ftp), host specifies the Internet name of the targeted host, and local info is a string (often a file name) passed to the protocol handler on the remote host.

299.What is URL path ?
The part of a URL passed by an HTTP request to invoke a servlet. A URL path consists of the context path + servlet path + path info, where Context path is the path prefix associated with a servlet context of which the servlet is a part. If this context is the default context rooted at the base of the Web server’s URL namespace, the path prefix will be an empty string. Otherwise, the path prefix starts with a / character but does not end with a / character. Servlet path is the path section that directly corresponds to the mapping that activated this request. This path starts with a / character. Path info is the part of the request path that is not part of the context path or the servlet path

300.What is URN ?
Uniform resource name. A unique identifier that identifies an entity but doesn’t tell where it is located. A system can use a URN to look up an entity locally before trying to find it on the Web. It also allows the Web location to change, while still allowing the entity to be found.

301.What is user data constraint ?
Indicates how data between a client and a Web container should be protected. The protection can be the prevention of tampering with the data or prevention of eavesdropping on the data.

302.What is user (security) ?
An individual (or application program) identity that has been authenticated. A user can have a set of roles associated with that identity, which entitles the user to access all resources protected by those roles.

303.What is validating parser ?
A parser that ensures that an XML document is valid in addition to being well formed. See also parser.

304.What is value-binding expression ?
A JavaServer Faces EL expression that refers to a property of a backing bean. A component tag uses this expression to bind the associated component’s value or the component instance to the bean property. If the component tag refers to the property via its value attribute, then the component’s value is bound to the property. If the component tag refers to the property via its binding attribute then the component itself is bound to the property.

305.What is virtual host ?
Multiple hosts plus domain names mapped to a single IP address.

306.What is W3C ?
World Wide Web Consortium. The international body that governs Internet standards. Its Web site is http://www.w3.org/.

307.What is WAR file ?
Web application archive file. A JAR archive that contains a Web module.

308.What is warning ?
A SAX parser warning is generated when the document’s DTD contains duplicate definitions and in similar situations that are not necessarily an error but which the document author might like to know about, because they could be. See also fatal error, error.

309.What is Web application ?
An application written for the Internet, including those built with Java technologies such as JavaServer Pages and servlets, as well as those built with non-Java technologies such as CGI and Perl.

310.What is Web application, distributable ?
A Web application that uses J2EE technology written so that it can be deployed in a Web container distributed across multiple Java virtual machines running on the same host or different hosts. The deployment descriptor for such an application uses the distributable element.

311.What is Web component ?
A component that provides services in response to requests; either a servlet or a JSP page.

312.What is Web container ?
A container that implements the Web component contract of the J2EE architecture. This contract specifies a runtime environment for Web components that includes security, concurrency, life-cycle management, transaction, deployment, and other services. A Web container provides the same services as a JSP container as well as a federated view of the J2EE platform APIs. A Web container is provided by a Web or J2EE server.

313.What is Web container, distributed ?
A Web container that can run a Web application that is tagged as distributable and that executes across multiple Java virtual machines running on the same host or on different hosts.

314.What is Web container provider ?
A vendor that supplies a Web container.

315.What is Web module ?
A deployable unit that consists of one or more Web components, other resources, and a Web application deployment descriptor contained in a hierarchy of directories and files in a standard Web application format.

316.What is Web resource ?
A static or dynamic object contained in a Web application that can be referenced by a URL. 

317.What is Web resource collection ?
A list of URL patterns and HTTP methods that describe a set of Web resources to be protected.

318.What is Web server ?
Software that provides services to access the Internet, an intranet, or an extranet. A Web server hosts Web sites, provides support for HTTP and other protocols, and executes server-side programs (such as CGI scripts or servlets) that perform certain functions. In the J2EE architecture, a Web server provides services to a Web container. For example, a Web container typically relies on a Web server to provide HTTP message handling. The J2EE architecture assumes that a Web container is hosted by a Web server from the same vendor, so it does not specify the contract between these two entities. A Web server can host one or more Web containers. 

319.What is Web server provider ?
A vendor that supplies a Web server.

320.What is Web service ?
An application that exists in a distributed environment, such as the Internet. A Web service accepts a request, performs its function based on the request, and returns a response. The request and the response can be part of the same operation, or they can occur separately, in which case the consumer does not need to wait for a response. Both the request and the response usually take the form of XML, a portable data-interchange format, and are delivered over a wire protocol, such as HTTP.

321.What is well-formed ?
An XML document that is syntactically correct. It does not have any angle brackets that are not part of tags, all tags have an ending tag or are themselves self-ending, and all tags are fully nested. Knowing that a document is well formed makes it possible to process it. However, a well-formed document may not be valid. To determine that, you need a validating parser and a DTD.

322.What is Xalan ?
An interpreting version of XSLT.

323.What is XHTML ?
An XML look-alike for HTML defined by one of several XHTML DTDs. To use XHTML for everything would of course defeat the purpose of XML, because the idea of XML is to identify information content, and not just to tell how to display it. You can reference it in a DTD, which allows you to say, for example, that the text in an element can contain < em > and < b > tags rather than being limited to plain text.

324.What is XLink ?
The part of the XLL specification that is concerned with specifying links between documents.

325.What is XLL ?
The XML Link Language specification, consisting of XLink and XPointer.

326.What is XML ?
Extensible Markup Language. A markup language that allows you to define the tags (markup) needed to identify the content, data, and text in XML documents. It differs from HTML, the markup language most often used to present information on the Internet. HTML has fixed tags that deal mainly with style or presentation. An XML document must undergo a transformation into a language with style tags under the control of a style sheet before it can be presented by a browser or other presentation mechanism. Two types of style sheets used with XML are CSS and XSL. Typically, XML is transformed into HTML for presentation. Although tags can be defined as needed in the generation of an XML document, a document type definition (DTD) can be used to define the elements allowed in a particular type of document. A document can be compared by using the rules in the DTD to determine its validity and to locate particular elements in the document. A Web services application’s J2EE deployment descriptors are expressed in XML with schemas defining allowed elements. Programs for processing XML documents use SAX or DOM APIs.

327.What is XML registry ?
An infrastructure that enables the building, deployment, and discovery of Web services. It is a neutral third party that facilitates dynamic and loosely coupled business-to-business (B2B) interactions.

328.What is XML Schema ?
The W3C specification for defining the structure, content, and semantics of XML documents.

329.What is XPath ?
An addressing mechanism for identifying the parts of an XML document.

330.What is XPointer ?
The part of the XLL specification that is concerned with identifying sections of documents so that they can be referenced in links or included in other documents.

331.What is XSL-FO ?
A subcomponent of XSL used for describing font sizes, page layouts, and how information flows from one page to another.

332.What is component (JavaServer Faces technology) ?
A user interface control that outputs data to a client or allows a user to input data to a JavaServer Faces application.

 

 

Core Java Interview Questions

Top most important Core Java interview questions and answers by Experts:

Here is a list of Top most important Core Java interview questions and answers by Experts.If you want to download Core Java interview questions pdf free ,you can register with RVH techguru. Our experts prepared these Core Java interview questions to accommodate freshers level to most experienced level technical interviews.

If you want to become an expert in Core Java ,Register for Core Java online training here.

 

1. What is Java technology ?
Java is a programming language, application development and deployment environment. Java programming language is similar to C++ syntax. Java development environment provides tools – Compiler, Interpreter, Packaging Tool etc.

2. What are the objectives of Java Technology ?
Simple: The language syntax is based on the familiar programming language ‘C++’. Though the syntax of ‘C++ was adopted, some features which were troublesome were avoided making the Java programming simple.
Object oriented: The object oriented features of Java are comparable to C++. One major difference between Java and C++ lies in multiple inheritance. Object oriented design is a technique that focuses design on data (i.e.objects) and on the interfaces to it.
Architectural Neutral: The Java compiler generates an intermediate byte code which does not depend on any architecture of a computer i.e., whether it is an IBM PC, a Macintosh, or a Solaris system. So the Java programs can be used on any machine irrespective of its architecture and hence the Java program is Architectural Neutral.
Portable type: The size of data types are always same irrespective of the system architecture. That is an int in Java is always 32 bit unlike in C/C++ where the size may be 16-bit or 32-bit depending on the compiler and machine. Hence when ported on different machines, there does not occur any change in the values the data types can hold. And also Java has libraries that enables to port its application on any systems like UNIX, Windows and the Macintosh systems.
Distributed: Java’s networking capabilities are both strong and easy to use. Java applications are capable of accessing objects across the net, via URLs as easy as a local file system.
Secure: Since Java is mostly used in network environment, a lot of emphasis has been placed on security to enable construction of virus free and tamper free systems.
Smaller code: The Java compiler generates an intermediate byte code to make it architecture neutral. Though Java interpreter is needed to run the byte code, it is one copy per machine and not per program.
Multithreaded: Multithreading is the ability for one program to do more than one task at once. Compared to other languages it is easy to implement multithreading in Java.
Interpreted: The Java Interpreter can execute Java byte code, directly on any machine to which the interpreter has been ported. Interpreted code is slower than compiled code.
High performance: The byte codes can be translated at run time into machine code for the particular CPU on which the application is running.

Applet programming: is one of the important features which has attracted the users of the Internet. Applets are Java programs that are typically loaded from the Internet by a browser.
3. What are the Major Features of Java Technology Architecture ?
• Java Run Time Environment
• Java Virtual Machine
• Just in Time Compiler
• Java Tools
• Garbage Collector
4. What is Java Virtual Machine (JVM) ?
A self-contained operating environment that behaves as if it is a separate computer. For example, Java applets run in a Java virtual machine (VM) that has no access to the host operating system.
Java Compilers compile JAVA source code into byte code. Java Virtual Machine(JVM) interpreters Java byte code and send necessary commands to underlying hardware or Just in time compiled to native machine code and execute it directly on the underlying hardware . Most JVM’s use Just in time compilation which provides execution speeds near to C or C++ application. Most widely used JVM is Oracle Corporations HotSpot, which is written in the C++ programming language.
5. What are the advantages of JVM?

This design has two advantages:
• System Independence: A Java application will run the same in any Java VM, regardless of the hardware and software underlying the system.
• Security: Because the VM has no contact with the operating system, there is little possibility of a Java program damaging other files or applications.
6. What are classpath variables?
Classpath is an environment variable that tells the Java Virtual Machine where to look for user-defined classes and packages in Java programs. The Classpath is the connection between the Java runtime and the filesystem. It defines where the compiler and interpreter look for .class files to load. The basic idea is that the file system hierarchy mirrors the Java package hierarchy, and the Classpath specifies which directories in the filesystem serve as roots for the Java package hierarchy.
7. What is Java Run Time Environment ?
Java Virtual Machine (JVM) along with Java Class Libraries which implement the Java application programming interface (API) form the Java Runtime Environment (JRE).
8. What are the steps involved in Java Application Execution ?
• Compiling Java Source Files into *.class file. (Byte Code)
• Loading class file into Java Run Time (JRE) using class loader
• Use Bytecode verifier to check for byte code specification
• Use Just In time Code Generator or Interpreter for byte code execution
9. What is Just in Time Compiler ?
Just in time Compiler (JIT) compiles JAVA byte code to native machine code and execute it directly on the underlying hardware. Just in time compilation which provides application execution speeds near to C or C++ application.
10. What is Java Development Kit (JDK) ?
Java Development Kit (JDK) is a super set of the JRE, which contains Java Run-time Environment (JRE) , Compilers and debuggers required to develop applets and applications.
11. What is Garbage Collector ?
For executing programs, application are allocated memory at runtime. After execution of programs, unused memory need to be allocated. Allocation and deallocation of memory is done by programmers developing application using C, C++ programming language . Java internally uses garbage collector to deallocate unused memory which make the life of programmer easy.
12. What is class loader ?
Class loader is used to load all the classes required execute the application into Java Virtual Machine (JVM). After the class is loaded memory required for the application is determined.
13. What is byte code verifier ?
Byte code verifier checks for illegal code like forges pointers, violated access rights on objects etc. in complied byte code.
14. What are the java verifications done by byte code verifier ?
1. Check whether classes follow JVM specification for classes
2. Check for stack overflows
3. Check for access restriction violations
4. Illegal data conversions
15. What is Java API?

An application programming interface (API) is a library of functions that Java provides for programmers for common tasks like file transfer, networking, and data structures.
16. Give Some examples of Java API.
• Java.applet – Applet class
• Java.awt – Windows, buttons, mouse, etc.
• Java.awt.image – image processing
• Java.awt.peer – GUI toolkit
• Java.io – System.out.print
• Java.lang – length method for arrays; exceptions
• Java.net – sockets
• Java.util – System.getProperty
17. What is an applet?

An applet is a small Java program that runs within a web page on your browser. Unlike a traditional desktop application, an applet is severely limited as to what it can perform on your desktop.
• Applet read and write files.
• Applet integrates with desktop services (e.g., e-mail).
• It is connected to other servers.
• It is also built with security in mind.
• If the user allows, an applet can be given more authority.
18. What is a class?

A class is a blueprint or prototype that defines the variables and the methods common to all objects of a certain kind.
19. What is an object?

An object is a software construct that encapsulates data, along with the ability to use or modify that data, into a software entity. An object is a self-contained entity which has its own private collection of properties (ie. data) and methods (i.e. operations) that encapsulate functionality into a reusable and dynamically loaded structure.
20. What an object contains?

An object has – State and Behavior
21. What is object oriented program?
An Object-Oriented Program consists of a group of cooperating objects, exchanging messages, for the purpose of achieving a common objective.
22. What are the benefits of OOPS?
• Real-world programming
• Reusability of code
• Modularity of code
• Resilience to change
• Information hiding
23. What are the features of OOPS?
• Encapsulation
• Abstraction
• Inheritance
• Polymorphism

24. What is encapsulation?
Encapsulation is the ability of an object to place a boundary around its properties (i.e. data) and methods (i.e. operations). Grady Booch, defined the encapsulation feature as:
“Encapsulation is the process of hiding all of the details of an object that do not contribute to its essential characteristics.”
25. What is abstraction?
An Abstraction denotes the essential characteristics of an object that distinguishes it from all other kinds of objects and thus provides crisply defined conceptual boundaries, relative to the perspective of the viewer.
26. What is the difference between encapsulation and abstraction?
Encapsulation hides the irrelevant details of an object and Abstraction makes only the relevant details of an object visible.
27. What is inheritance?

Inheritance is the capability of a class to use the properties and methods of another class while adding its own functionality. It enables you to add new features and functionality to an existing class without modifying the existing class.
28. What is superclass and subclass?
• A superclass or parent class is the one from which another class inherits attributes and behavior.
• A subclass or child class is a class that inherits attributes and behavior from a superclass.

29. What is JIT compiler?

Just-In-Time(JIT) compiler:It is used to improve the performance. JIT compiles parts of the byte code that have similar functionality at the same time, and hence reduces the amount of time needed for compilation.Here the term “compiler” refers to a translator from the instruction set of a Java virtual machine (JVM) to the instruction set of a specific CPU.
30. What are the types of inheritance?
• Single inheritance
• Multiple inheritance

31.What is platform?

A platform is basically the hardware or software environment in which a program runs. There are two types of platforms software-based and hardware-based. Java provides software-based platform.

32. What is classloader?

The classloader is a subsystem of JVM that is used to load classes and interfaces.There are many types of classloaders e.g. Bootstrap classloader, Extension classloader, System classloader, Plugin classloader etc.

33. What is polymorphism?
Derived from two Latin words – Poly, which means many, and morph, which means forms.
• It is the capability of an action or method to do different things based on the object that it is acting upon.
• In object-oriented programming, polymorphism refers to a programming language’s ability to process objects differently depending on their data type or class.
34. Describe method overloading with example?
Java allows to define several methods with same name within a class. Methods are identified with the parameters set based on:
• the number of parameters
• types of parameters and
• order of parameters.
Compiler selects the proper method. This is called as Method overloading. Method overloading is used perform same task with different available data. For Example:
int sum(int a,int b) { return a+b;}
int sum(int a,int b,int c) { return a+b+c;}
float sum(float a, float b, float c) { return a+b+c;}
35. How to identify starting method of a program ?
Method starting with following code
public static void main (String args[])
{
}

36. How do we access data members of a class in java?
Dot Operator(.) is used to access the data members of a class outside the class by specifying the data member name or the method name.

37. What is “this” reference in java?

“this” is a reference to the current object. “this” is used to refer to the current object when it has to be passed as a parameter to a method.
otherobj1.anymethod(this);
refer to the current object when it has to be returned in a method. Refer the instance variables if parameter names are same as instance variables to avoid ambiguity.
public void method1(String name){
this.name=name;
}
The this keyword included with parenthesis i.e. this() with or without parameters is used to call another constructer. The default construct for the Car class can be redefined as below
public Car(){
this(“NoBrand”,””NoColor”,4,0);
}
The this() can be called only from a constructor and must be the first statement in the constructor
38. What are the uses of Java packages?
“A package is a namespace that organizes the a set of related classes and interfaces. It also defines the scope of a class. An application consists of thousands of classes and interfaces, and therefore, it is very important to organize them logically into packages. By definition, package is a grouping of related types providing access protection and name space management.” Packages enable you to organize the class files provided by Java.
39. What is the significance of import keyword?

The classes in the packages are to be included into the applications as required. The classes of a package are included using import keyword. The import keyword followed by fully qualified class name is to be placed before the application class definition.
import classname ;
// Class Definition.
Ex: import Java.util.Date;
import Java.io.*;
// Class Definition
above indicates to import all the classes in a package.
All the classes in Java.lang package are included implicitly.
40. What is user defined package in java?
When you write a Java program, you create many classes. You can organize these classes by creating your own packages. The packages that you create are called user-defined packages. A user-defined package contains one or more classes that can be imported in a Java program.
package land.vehicle;
public class Car
{
String brand;
String color;
int wheels;
}
41. How to compile a Java Source file ?
From command prompt, Go to location in which Java file is located. Enter command “javac” followed by Java source file name. For example, To compile person class, type command “javac Person.java” . Class files will be generated in the same location
42. How to compile all the files in a Folder?
javac *.java”
43. How to place compiled Java file in a different location ?
To compile Java classes and place all the file in a different location use command “javac -d ../Java/All/*.java”
44. How to run a compiled Java file ?
Go to location in which Java file is located from command prompt. Enter command “java” followed by class name . For example to execute Employee class, type command “java Employee”
45. Why Information hiding is used and how Information hiding is implemented in Java ?
In order to avoid direct access of an attribute in a class, attributes are defined as private and use getter and setter to restrict the access of attributes in a class. Example class is given below
public class Person {
private String FirstName;

public String getFirstName()
{
return FirstName;
}
public void setFirstName(String FirstName)
{
this.FirstName = FirstName;
}
}
46. What is a Constructor ?
A constructor is a special method that initializes the instance variables. The method is called automatically when an object of that class is created. A constructor method has the same name as the that of the class.
A constructor always returns objects of the class type hence there is no return type specified in its definition. A constructor is most often defined with the accessibility modifier “public” so that every program can create an instance but is not mandatory. A constructor is provided to initialize the instance variables in the class when it is called.
If no constructor is provided, a default constructor is used to create instances of the class. A default Constructor initializes the instance variables with default values of the data types. If at least one constructor is provided , default constructor is not provided by JVM. A class can have multiple constructors.
class Car {
String brand;
String color;
int wheels;
int speed;
int gear;
public Car() {
brand=“NoBrand”;
color=“NoColor”;
wheels=4;
speed=80;
}

public Car(String b, String c, int w, int s, int g)
{
brand=b;
color=c;
wheels=w;
speed=s;
}

void accelerate(){}
void brake(){}
void changeGear(){}
}
47. What is access modifier and what are its types?
An attribute that determines whether or not a class member is accessible in an expression or declaration. Different types of access modifiers are:
• Public – Members are accessible to the class and to other classes.
• Private – Members are accessible only to the class.
• Protected – Members are accessible only to the class and its subclass(es).
• Default – Members are accessible only to the class and other classes within that package. This is the default access specifier.

48. What is final keyword?
A final data members cannot be modified. A final method cannot be overridden in the subclass. A class declared as final cannot be inherited .
49. What is static keyword?
Static keyword is used to define data members and methods that belongs to a class and not to any specific instance of a class. Static Methods and data members can be called without instancing the class.A static member exists when no objects of that class exist.
50. What is abstract keyword?
Abstract keyword is used to declare class that provides common behavior across a set of subclasses. Abstract class provides a common root for a group of classes. An abstract keyword with a method does not have any definition.
51. What is synchronized keyword?

It controls the access to a block in a multithreaded environment.
52. What is native keyword?

Native keyword is used only with methods. It signals the compiler that the method has been coded in a language other than Java. It indicates that method lies outside the Java Runtime Environment.
53. What is a transient variable?

A transient variable is a variable that may not be serialized.i.e JVM understands that the indicated variable is not part of the persistent state of the object. For example
class A implements Serializable {
transient int i; // will not persist
int j; // will persist
}
Here, if an object of type A is written to a persistent storage area, the contents of i would not be saved, but the contents of j would.
54. What is sctrictfp keyword?
strictfp can be used to modify a class or a method, but never a variable. Marking a class as strictfp means that any method code in the class will conform to the IEEE 754 standard rules for floating points. Without that modifier floating points used in the methods might behave in a platform-dependent way.
If not at class class level , strictfp behavior can be applied at method level, by declaring a method as strictfp. Usage of strictfp is required when floating point values should be consistent across multiple platforms.
55. Explain method overriding with an example?
Method overriding is defined as creating a non-static method in the subclass that has the same return type and signature as a method defined in the superclass. Signature of a method includes name of method and number, sequence, type of arguments.
public class Person {
private String name;
private String ssn;
public void setName(String name) {
this.name = name;
}

public String getName() {
return name; }

public String getId() {
return ssn;}
getId method is overridden in subclass:
public class Employee extends Person
{
private String empId;

public void setId(String empId)
{
this.empId=empId;
}

public String getId() {
return empId;
}
}
56. What is the use of super keyword. Give an example?

It allows you to access methods and properties of the parent class.
public class Person {
private String name;

public Person(String name) {
this.name = name; }

public String getName() {
return name;
} }

public class Employee extends Person {
private String empID;

public Employee(String name) {
super(name); // Calls Person constructor
}
public void setID(String empID){
this.empID=empID;
}
public String getID(){
return empID;
}
}
57. What is an interface?
A programmer’s tool for specifying certain behaviors that an object must have in order to be useful for some particular task.Interface is a conceptual entity. It can contain only constants (final variables) and non-implemented methods (Non – implemented methods are also known as abstract methods).
For example, you might specify Driver interface as part of a Vehicle object hierarchy. A human can be a Driver, but so can a Robot.
58. What is an abstract class?
• An Abstract class is a conceptual class.
• An Abstract class cannot be instantiated – objects cannot be created.
• Abstract classes provides a common root for a group of classes, nicely tied together in a package.
• When we define a class to be “final”, it cannot be extended. In certain situation, we want properties of classes to be always extended and used. Such classes are called Abstract Classes.

59. What are the properties of abstract class?
• A class with one or more abstract methods is automatically abstract and it cannot be instantiated.
• A class declared abstract, even with no abstract methods can not be instantiated.
• A subclass of an abstract class can be instantiated if it overrides all abstract methods by implementation them.
• A subclass that does not implement all of the superclass abstract methods is itself abstract; and it cannot be instantiated.
• We cannot declare abstract constructors or abstract static methods.

60. What is object class in java?
Every class that we create extends the class Object by default. That is the Object class is at the highest of the hierarchy. This facilitates to pass an object of any class to be passed as an argument to methods.
61. What are the methods of object class?
The methods in this class are:
• equals(Object ref) – returns if both objects are equal
• finalize( ) – method called when an object’s memory is destroyed
• getClass( ) – returns class to which the object belongs
• hashCode( ) – returns the hashcode of the class
• notify( ) – method to give message to a synchronized methods
• notifyAll( ) – method to give message to all synchronized methods
• toString() – return the string equivalent of the object name
• wait() – suspends a thread for a while
• wait(…) – suspends a thread for specified time in seconds
62. What does java.util package provides?
The java.util package provides various utility classes and interfaces that support date and calendar operations, String manipulations and Collections manipulations.
63. How do we convert object to string?
Any Java reference type or primitive that appears where a String is expected will be converted into a string.
System.out.println(“1 + 2 = ” + (1 + 2));
For an reference type (object) this is done by inserting code to call String toString() on the reference.
All reference types inherit this method from java.lang.Object and override this method to produce a string that represents the data in a form suitable for printing.
To provide this service for Java’s primitive types, the compiler must wrap the type in a so-called wrapper class, and call the wrapper class’s toString method.
String arg1 = new Integer(1 + 2).toString();
For user defined classes they will inherit the standard Object.toString() which produces something like “ClassName@123456” (where the number is the hashcode representation of the object). To have something meaningful the classes have to provide a method with the signature public String toString().
public class Car() {

String toString()
{
return brand + ” : ” + color + ” : ”+wheels+” : “+ speed;
}
}
64. How can we convert string to object?
Many data type wrapper classes provide the valueOf(String s) method which converts the given string into a numeric value. The syntax is straightforward. It requires using the static Integer.valueOf(String s) and intValue() methods from the java.lang.Integer class.
To convert the String “22” into the int 22 you would write
int i = Integer.valueOf(“22”).intValue();
Doubles, floats and longs are converted similarly. To convert a String like “22” into the long value 22 you would write
long l = Long.valueOf(“22”).longValue();
To convert “22.5” into a float or a double you would write:
double x = Double.valueOf(“22.5”).doubleValue(); float y = Float.valueOf(“22.5”).floatValue();
If the passed value is non-numeric like “Four” it will throw a NumberFormatException.
65. What is Regular expression?
Regular expressions are a way to describe a set of strings based on common characteristics shared by each string in the set. They can be used to search, edit, or manipulate text and data.
The regular expression syntax supported by the java.util.regex API
66. What does rejex package consists of?
The java.util.regex package primarily consists of three classes: Pattern, Matcher, and PatternSyntaxException. A Pattern object is a compiled representation of a regular expression. The Pattern class provides no public constructors.
To create a pattern, you must first invoke one of its public static compile methods, which will then return a Pattern object. These methods accept a regular expression as the first argument; the first few lessons of this trail will teach you the required syntax.
A Matcher object is the engine that interprets the pattern and performs match operations against an input string. Like the Pattern class, Matcher defines no public constructors. You obtain a Matcher object by invoking the matcher method on a Pattern object. A PatternSyntaxException object is an unchecked exception that indicates a syntax error in a regular expression pattern.
67. What is StringBuffer class is used for?
• It is used for creating and manipulating dynamic string data i.e., modifiable Strings.
• It can store characters based on capacity. Capacity expands dynamically to handle additional characters. It cannot use operators + and += for string concatenation.
• It has fewer utility methods (e.g. substring, trim, ….)
68. What is the difference between StringBuffer and StringBuilder class?
StringBuffer class is not threadsafe whereas StringBuilder class is threadsafe. That means the methods of StringBuilder class are synchronized.
69. What is matcher in regex package?

A matcher is created from a pattern by invoking the pattern’s matcher method. Once created, a matcher can be used to perform three different kinds of match operations:
• The matches method attempts to match the entire input sequence against the pattern.
• The looking at method attempts to match the input sequence, starting at the beginning, against the pattern.
• The find method scans the input sequence looking for the next subsequence that matches the pattern

70. How to add comments in Java File ?
Comments can be inserted in 3 ways as shown below

// Comment Type1

/* Multi Line Comments
* Comment Line 2 */

/* Documentation Comment
* Comment Line 2 */

This comment will be added in the automatic document generation
71. What are the limitations of array?
Arrays do not grow while applications demand. It has inadequate support for inserting, deleting, sorting, and searching operations.
72. What is collection framework?
Collections Framework provides a unified system for organizing and handling collections and is based on four elements:
• Interfaces that characterize common collection types
• Abstract Classes which can be used as a starting point for custom collections and which are extended by the JDK implementation classes.
• Classes which provide implementations of the Interfaces.
• Algorithms that provide behaviors commonly required when using collections i.e. search, sort, iterate, etc.
Another item in collections framework is the Iterator interface. An iterator gives you a general-purpose, standardized way of accessing the elements within a collection, one at a time.
73. What is set interface about?
Mathematically a set is a collection of non-duplicate elements.The Set interface is used to represent a collection which does not contain duplicate elements. The Set interface extends the Collection interface. It stipulates that an instance of Set contains no duplicate elements.
The classes that implement Set must ensure that no duplicate elements can be added to the set. That is no two elements e1 and e2 can be in the set such that e1.equals(e2) is true.
74. What is HashSet, LinkedHashSet and TreeSet?
The Java platform contains three general-purpose Set implementations: HashSet, TreeSet, and LinkedHashSet.
• HashSet: This is an unsorted, unordered Set. This may be chosen when order of the elements are not important .
• LinkedHashSet: This is ordered. The elements are linked to one another (Double-Linked). This will maintain the list in the order in which they were inserted.
• TreeSet: This is a sorted set. The elements in this will be in ascending order in the natural order. You can also define a custom order by means of a Comparator passed as a parameter to the constructor.
75. Which one to choose and when among HashSet, LinkedHashSet and TreeSet?
• HashSet is a good choice for representing sets if you don’t care about element ordering. But if ordering is important, then LinkedHashSet or TreeSet are better choices. However, LinkedHashSet or TreeSet come with an additional speed and space cost.
• Iteration over a LinkedHashSet is generally faster than iteration over a HashSet.
• Tree-based data structures get slower as the number of elements get larger
• HashSet and LinkedHashSet do not represent their elements in sorted order
• Since TreeSet keeps its elements sorted, it can offer other features such as the first and last methods,i.e the lowest and highest elements in a set, respectively.

76. What is Enumeration interface?
The Enumeration interface defines a way to traverse all the members of a collection of objects. The hasMoreElements() method checks to see if there are more elements and returns a boolean.

If there are more elements, nextElement() will return the next element as an Object. If there are no more elements when nextElement() is called, the runtime NoSuchElementException will be thrown.
77. Explain Iterator interface?
Iterator is a special object to provide a way to access the elements of a collection sequentially. Iterator implements one of two interfaces: Iterator or ListIterator. An Iterator is similar to the Enumeration interface, Iterators differ from enumerations in two ways:
Iterators allow the caller to remove elements from the underlying collection during the iteration with well-defined semantics.
Method names have been improved.
boolean hasNext() Returns true if the iteration has more elements. Object next() Returns the next element in the iteration. void remove() Removes from the underlying collection the last element returned by the iterator (optional operation).
78. What is SortedSet interface?
SortedSet is a subinterface of Set, which guarantees that the elements in the set are sorted. TreeSet is a concrete class that implements the SortedSet interface. You can use an iterator to traverse the elements in the sorted order.
79. How elements can be sorted in java collections?

The elements can be sorted in two ways. One way is to use the Comparable interface. Objects can be compared using by the compareTo() method. This approach is referred to as a natural order.
The other way is to specify a comparator for the elements in the set if the class for the elements does not implement the Comparable interface, or you don’t want to use the compareTo() method in the class that implements the Comparable interface. This approach is referred to as order by comparator
80. What is a list interface?
• A list allows duplicate elements in a collection where duplicate elements are to be stored in a collection, list can be used. A list also allows to specify where the element is to be stored. The user can access the element by index.
• The List interface allows to create a list of elements.The List interface extends the Collection interface.
81. Compare ArrayList vs LinkedList?
• ArrayList provides support random access through an index without inserting or removing elements from any place other than an end.
• LinkedList provides support for random access through an index with inserting and deletion elements from any place .
• If your application does not require insertion or deletion of elements, the Array is the most efficient data structure.
82. What is a vector class?
The Vector class implements a growable array of objects. Like an array, it contains components that can be accessed using an integer index. However, the size of a Vector can grow or shrink as needed to accommodate adding and removing items after the Vector has been created.
83. What is a Stack class?

The Stack class represents a last-in-first-out (LIFO) stack of objects. The elements are accessed only from the top of the stack. You can retrieve, insert, or remove an element from the top of the stack.
84. What is a Map interface?
A Map is a storage that maps keys to values. There cannot be duplicate keys in a Map and each key maps to at most one value. The Map interface is not an extension of Collection interface. Instead the interface starts of it’s own interface hierarchy. for maintaining key-value associations. The interface describes a mapping from keys to values, without duplicate keys, by definition. The Map interface maps keys to the elements. The keys are like indexes. In List, the indexes are integer. In Map, the keys can be any objects.
85. Describe about HashMap and TreeMap?

The HashMap and TreeMap classes are two concrete implementations of the Map interface. Both will require key &value. Keys must be unique. The HashMap class is efficient for locating a value, inserting a mapping, and deleting a mapping. The TreeMap class, implementing SortedMap, is efficient for traversing the keys in a sorted order.
HashMap allows null as both keys and values.TreeMap is slower than HashMap. TreeMap allows us to specify an optional Comparator object during its creation. This comparator decides the order by which the keys need to be sorted.
86. What is the purpose of Collections class in util package?
The Collections class contains various static methods for operating on collections and maps, for creating synchronized collection classes, and for creating read-only collection classes.
87. How do we order/sort objects in collections?

To provide for ordering/sorting of the objects Java API provides two interfaces Comparable and Comparator
• Comparable interface is in java.lang
• Comparator interface is in java.util
88. When to use Comparable and Comparator in code?
The Comparable interface is simpler and less work
• Your class implements Comparable
• You provide a public int compareTo(Object o) method
• Use no argument in your TreeSet or TreeMap constructor
• You will use the same comparison method every time
The Comparator interface is more flexible but slightly more work
• Create as many different classes that implement Comparator as you like
• You can sort the TreeSet or TreeMap differently with each
• Construct TreeSet or TreeMap using the comparator you want
• For example, sort Students by score or by name
Suppose you have students sorted by score, in a TreeSet you call studentsByScore. Now you want to sort them again, this time by name
Comparator<Student> myStudentNameComparator = new MyStudentNameComparator();
TreeSet studentsByName = new TreeSet(myStudentNameComparator);
studentsByName.addAll(studentsByScore);
89. What are the new features added in Java 1.5?
Generic classes
• New approach to loops – Enhanced for loop
• Static imports
• Arrays, string builder, queues and overriding return type
Annotation
• Output formatting – format() and printf()
• Autoboxing of primitive types
• Enumerated types
• Variable length of arguments

90. What is Generic classes?

Similar in usage to C++ templates, but do not generate code for each implementation. It ensure stored/retrieved type of objects.Check done at compile-time – avoid nasty casting surprises during runtime. Generics are removed from compiled classes. Java 5 is upwardly compatible with Java 1.4, so old programs must continue to work. It can be used in legacy code to check for place where incorrect type is inserted
91. What is the big advantage of Generics?
Big advantage: collections are now type safe. For example, you can create a Stack that holds only Strings as follows:
Stack<String> names = new Stack<String>();
You can write methods that require a type-safe collection as follows:
void printNames(Stack<String> names) {
String nextName = names.pop(); // no casting needed!
names.push(“Hello”); // works just the same as before
names.push(Color.RED); // compile-time error!
92. What is StringBuilder class?
It is an improvement upon StringBuffer. It allows quicker concatenation of strings. It is not safe for use by multiple threads at the same time since the methods are not synchronized.
Why use it?
Creating new Strings in a loop can be inefficient because of the number new objects that are created and discarded.
StringBuilder.append(<type> <value>)
StringBuilder.insert(<type> <value>)
93. What is Queue interface?
• It extends Collection interface. It is designed for holding elements prior to processing. It is typically ordered in a FIFO manner.
• Main Methods are – remove() and pull(). Both return the head of the queue. When empty, the remove() method throws an exception while poll() returns null.
94. Describe covariant return types with an example?
It allows the user to have a method in inherited class with same signature as in parent’s class but differing only in return types. It makes programs more readable and solves casting problem.
class Shape
{
public Shape transform(int x, int y)
}
class Rectangle extends Shape
{
public Rectangle transform(int x, int y)
}
95. What is boxing and unboxing ?
Converting a primitive data type to its corresponding wrapper class object is called boxing or autoboxing. Example of boxing,
int i = 0;
Integer O = new Integer(i);
Unboxing is the exact opposite of boxing where wrapper class object is converted into primitive data type. Example of unboxing,
i = O.intValue();
96. How autoboxing was done before java 5 and in java 5 version?
Before 5.0
ArrayList<Integer> list = new ArrayList<Integer>();list.add(0, new Integer(42)); int total = (list.get(0)).intValue();
From 5.0 version:
ArrayList<Integer> list = new ArrayList<Integer>();list.add(0, 42);int total = list.get(0);
97. How java distinguishes between primitive types and objects?
Java distinguishes between primitive types and Objects.
• Primitive types, i.e., int, double, are compact, support arithmetic operators.
• Object classes (Integer, Double) have more methods: Integer.toString()
You need a “wrapper” to use Object methods:
Integer ii = new Integer( i );
ii.hashCode()
Similarly, you need to “unwrap” an Object to use primitive operation
int j = ii.intValue() * 7;
Java 1.5 makes this automatic:
ArrayList<Integer> list = new ArrayList<Integer>();
list.add(0, 42);
int total = list.get(0);
98. What is Enum?

An enumeration, or “enum,” is simply a set of constants to represent various values. Here’s the old way of doing it:
public final int SPRING = 0;
public final int SUMMER = 1;
public final int FALL = 2;
public final int WINTER = 3;
This is a nuisance, and is error prone as well. Here’s the new way of doing it,
enum Season { winter, spring, summer, fall }
Enums are classes, extends java.lang.Enum.Enums are final, can’t be subclassed. Only one Constructor and is protected. It implement java.lang.Comparable: compareTo() and implements Serializable.
99. What is an exception?
An exception can be defined as an abnormal event that occurs during program execution and disrupts the normal flow of instructions.
100. What are the uses of exceptions?
• Consistent error reporting style.
• Easy to pass errors up the stack.
• Pinpoint errors better in stack trace.
• As long as you “fail fast” and throw as soon as you find a problem.
• Wrap useful information up in your exception classes, use that information later when handling the exception.
• Exceptions don’t always have to be errors, maybe your program can cope with the exception and keep going!
• Separating error handling code from Regular code

Adv Java Interview Questions

Top most important Adv Java interview questions and answers by Experts:

Here is a list of Top most important Adv Java interview questions and answers by Experts.If you want to download Adv Java interview questions pdf free ,you can register with RVH techguru. Our experts prepared these Adv Java interview questions to accommodate freshers level to most experienced level technical interviews.

If you want to become an expert in Adv Java ,Register for Adv Java online training here.

1) Explain run time polymorphism in Java ?
Polymorphism can be explained as an object’s ability to adapt to the program’s context and take multiple forms. The method overriding is an example of run time polymorphism. You can have a method in a subclass, which overrides the method in its super classes with the same name and signature. At run time, Java virtual machine determines the appropriate method to be called.
2) What are the rules (method access permission and exception) that needs to be followed, during method overloading and overriding ?

During method Overloading, method name should remain same. But method signature can vary. Components of signature that can vary are
• Number of arguments
• Datatype of arguments
• Order of arguments
During method Overriding, make sure that the method is not throwing checked exceptions that are new or higher than those declared by the overridden method.But we can’t override Static and Final methods.

3) What is the difference between an Interface and abstract class?
Abstract Interface
Supports Single inheritance Supports Multiple inheritance
Supports abstract and Non-abstract methods Allows only abstract methods
Supports Non-static and non-final variables also. Variables must be static and final(implicitly)
Supports non public member Only public members are allowed
Using extends keyword Using implements keyword
It can invoke if main exists Pure abstract
Faster Flexible
4) Explain the difference between compile time and run time polymorphism in Java ?
Compile time Polymorphism Run time Polymorphism
Method are called at compile time Method are called at run time
Ex: Overloading Ex: Overriding
5) What is the difference between Overloading and Overriding ?
Overloading Overriding
Methods are overloaded during compile time Method overriding takes place during runtime
All the overloaded methods should be placed in the same class We can override methods in sub class
We can overload static methods Static methods can’t be overridden
Methods are bonded together using static binding. Overridden method are bonded via dynamic bonding based upon actual Object.
To overload a method, method signature needs to be changed There is no need to change the signature
Private and final method can be overloaded. Private and final method can’t be overridden
Method is relatively fast. Method is relatively slow.
6) What is the difference between class and object ?
Class Object
Template/Blue print of an object. It is an instance of a class. Object have states and behaviors.
A logical construct. A Physical reality.

7) What are the major object oriented concepts in Java ?
Abstraction
It denotes the critical properties of an object which differentiate from other object and thus provide crisply defined conceptual boundaries relative to the perspective viewer.

Encapsulation
Encapsulation can be explained as a mechanism which binds the code and the data it manipulates. It also keeps them safe from external intervention and misuse.

Inheritance:
One object inherits the properties and methods of another Object.

Polymorphism
It is an ability of an object to take on many forms. Ex: Compile time polymorphism – method over loading. Run time polymorphism – method overriding

8) Why Java is not supporting multiple inheritance ?

Main features of java are very Simple. if multiple inheritance is supported, it creates ambiguity around Diamond problem and it does complicate the design and creates problem during casting, chaining etc. So Java will support multi-inheritance via single inheritance with interfaces to overcome above issues.

9) What is meant by final keyword in Java ?
• If final variable is used in front of variable, we can’t change the value.
• If the variable is used in front of method, it can’t be overridden.
• If it is used in front of Class, class can’t be extended by any other class.

10) What is meant by static keyword in Java ?

A static is a member of a class that’s not associated with instance. So static members can be accessed without creating an instance of a class.
11) What is meant by JVM ?
JVM(Java Virtual Machine) is a run time environment for the compiled java class files. Main function of JVM is to convert byte code(.class file) to machine code and send appropriate commands to underlying machine for execution.
12) Can abstract class implements another interface ?
Yes. It’s just a special case of implementation by which subclasses are forced to implement the methods.
13) Can abstract class extend another abstract class?
Yes. It is perfectly valid for an abstract class to extend another abstract class.
14) Can a interface extend another interface?
Yes. An interface can extend another interface in Java.
15) What Is Stack?
• Each Java thread have a private JVM stack, created along with thread.
• Stack stores frames. Frames are used for storing data (Variable and Object Data as well as partial results) and to perform operations such as
o Dynamic linking
o Dispatch exceptions when error occurs
o Return values when methods are invoked. Since the stack can’t be accessed directly, it push and pop frames.
• It is not mandatory that the Java virtual machine stack had to be continuous.
• JVM throws StackOverflowError, if any computation inside a thread needs larger JVM stack than allocated .

16) What Is Heap?
• When JVM starts, heap is created
• Heap is the runtime data area of the JVM
• It is shared by all the threads inside the JVM
• It allocates memory for all class instances and arrays
• Heap storage for objects is reclaimed by garbage collector when it is not used.
• JVM throws OutOfMemoryError, If a computation needs more heap than what can be supplied by the automatic storage management system.

17) Can you explain about Upcasting and Downcasting in Java ?
• Upcasting : Casting a Sub class to Super class. Upcasting is called as widening.
• Downcasting : Casting a Super class to Sub class. Downcasting is called as narrowing.

18) Can you explain about Implicit and Explicit type casting ?

Implicit casting (widening conversion) :

When JVM encounters a data type of lower size which occupies less memory, it is assigned to a data type of higher size implicitly by the JVM. This is also known as automatic type conversion. For Example
int i = 1; // 4 bytes
double d = i; // 8 bytes

Explicit casting:

When a data type of higher size which occupies more memory, needs to be assigned to a data type of lower size, it is called explicit casting. This type of casting won’t be done implicitly by the JVM. This casting operation should be performed by the programmer. For example
double d = 1.0;
int i = (int) d;

19) Can you explain about markable interface in Java ?
Interfaces with no methods are known as Marker interface. Some of the markable interfaces are
java.lang.Cloneable
java.io.Serializable
java.util.EventListener
20) Can you explain about reflection in Java ?

If a programmer wants to access entities or invoke methods in a program dynamically, i.e. if the programmer is unaware of the methods and variables that needs to be invoked at runtime but unaware of it while coding, we can use reflection. For example
Method method = ABC.getClass().getMethod(“doSomething”, null);
method.invoke(ABC, null);
21) Can you explain about java.lang.class ?

When JVM creates an instance of a class, it creates an object “java.lang.Class object” which describes the type of the object. This class object is shared by all the objects of a class. If you want to access the class object of an instance, use getClass() method of the object. This method is inherited from java.lang.Object
Ex: Created two instances class called Programmer
Programmer A = new Programmer();
Programmer B = new Programmer();
// For check Instances
if(A.getClass() == B.getClass())
{
System.out.println(“A and B are instances of same class”);
}else{
System.out.println(“A and B are instances of different class”);
}

22) Can you explain about Singleton class in Java ?

Singleton class is used to control no of object created for a class, limiting the number to one. But if the situation changes in future, it allows to create more objects without affecting existing clients.
23) Can you explain about Static class in Java ?

A class can be made static provided that the class is a nested class. A nested class is class which is defined inside a class. But top class can’t me made static. Example :
public class Test
{
static class StaticInnerClass
{
public static void innerMethod()
{ System.out.println(“Static Inner Class!”); }
}
public static void main(String args[])
{
Test.StaticInnerClass.innerMethod();
}
}

24) Can you explain about volatile Keywords in Java ?
• Volatile keyword is used to indicate the threads using a common variable that, the variable which is declared as Volatile can be updated by multiple threads. So threads should not cache the threads locally and in turn should get the value for the variable from main memory.
• If a variable is declared as volatile, it won’t be serialized.

25) What are the advantages of organizing classes and interfaces into a package ?
• Determination of a category of a file is simplified.
• Name space collision is avoided.
• Access restriction can be applied with the use of packages.
• Packages provide reusability of code

26) Can you explain about Java naming convention ?

Common Naming conventions as below :
• package names always start with lowercase characters. Ex: java.util
• Class names always begin with a capital letter and followed next word start with a capital letter. Ex: GregorianCalendar
• Java Naming convention specifies that instances and other variables must start with lowercase followed next word should be capital letter. Ex : MyClass myClass = new MyClass();
• Constant variables are declared using “static final” modifiers. And such variables must contain only UpperCase charachters and multiple words must be seperated using ‘_’. Ex: static final char END_OF_FILE = ‘e’;
• Methods in Java also follow the same like Objects and variables. For example
void myMethod(){
String strVal = “ABCD”;
}
27) How to call a garbage collector in java?
System.gc() or Runtime.getRuntime().gc().

28) What are the new features available in Java 1.7 ?
• Strings in switch Statement
• Type Inference for Generic Instance Creation
• Multiple Exception Handling
• Support for Dynamic Languages
• Try with Resources
• Java nio Package
• Binary Literals, underscore in literals
• Diamond Syntax
• Automatic null Handling

29) What are the advantage of Inheritance in Java ?
• Re-usability : Inheritance helps derived class to use methods of base class without rewriting them
• Extensibility : Extending the base class logic as per business logic of the derived class
• Data hiding : Allows base class to keep some private data which can’t be altered by the derived class
30) Why String is immutable in Java ?
 String is a special type of immutable class. Immutable class is a class which once created, it’s contents can not be changed. Immutable objects are the objects whose state can’t be changed once constructed.
 
31) Can you explain about information hiding in Java ?

Information hiding helps objects to hide critical information from other other objects accessing it. It effectively decouples the method being invoked from the internal workings of a function. By doing so, object can change the hidden portions of the function without changing the calling code. Encapsulation is a common technique programmers use to implement information hiding.
32) Can you explain about encapsulation in Java ?

Encapsulation helps java to bind code and data it manipulates, restrict outside interference and misuse of data. It also hides irrelevant details of an object.
33) Can you explain about the access modifier in Java ?

Access modifiers specifies the access levels of a variable or method. Java access modifiers are public, private, protected, default modifier (Default access modifier).
Access Modifiers Same Class Same Package Subclass Other packages
public Yes Yes Yes Yes
protected Yes Yes Yes No
default Yes Yes No No
private Yes No No No

34) What is the difference between super() and this() in Java ?
If you want to access methods of the base class from derived class “super” keyword is used. To access methods of the same class “this” keyword is used.

35) Can you explain about the constructor in Java ?
• Java constructors are special methods that are called when an object is instantiated.
• When objects are instantiated, arguments passed to the constructor will initialized the variables in an object.
• Name of the constructor should be same as the name of the Class. It can’t have any return type.
• A class can have multiple constructors. Calling a constructor from another constructor in the same class is called Constructor chaining.
• All classes have a default empty constructor.

36) Can constructor take parameters ?

Yes. Constructor can take arguments.

37) Can you explain about the default constructor in Java ?

When a constructor is not specified explicitly, java compiler automatically creates a “Default Constructor”. When we creates and object instance, default constructor initialize variables with it’s default values.

38) What are the common reasons to define a default constructor ?
• To construct an object with default values.
• To initialize an object that doesn’t need parameters in that initialization process.
• To redefine the scope of the constructor. By making the default constructor private, Java prevents everyone other than the class from constructing an object.

39) Can you explain about native method in Java ?
• Native is non access modifier. It can be applied only to method.
• It indicates the Platform-Dependent implementation of method or code.

40) Can you explain about strictfp keyword in Java ?
If we want floating point values to be consistent across platforms, then we need to use “strictfp”as per IEEE 754 standard. When a program runs on multiple platforms, precision of floating point differ which in turn given different results. strictfp helps to enforce the precision across all platforms. For example
Class Level – public strictfp class StrictFpModifierExample{}
Method Level – public strictfp void example() {}

41) Can you explain about String pool ?

String Pool is a pool of strings stored in Java heap memory. String objects can be created either by new operator or by specifying the values in double quotes.
Case 1 : When a new string is created using double quotes, JVM searches string pool for the string with the same value. if it finds a string which matches the values, it will return the reference of the string. Else it will create a new string in the pool and returns that reference.
String s1 = “Cat”;
String s2 = “Cat”;
if(s1 == s2) System.out.println(“equal”); //Prints equal.
Case 2 : When new operator is used to create a string, String class will be forced to create a new String object. To put the newly created string into the pool or assign it to another string, use intern().
String n1 = new String(“ABCD”);
String n2 = new String(“ABCD”);
if(n1 == n2) System.out.println(“equal”); //No output.

42) Differences between String, StringBuffer and StringBuilder in Java ?

String StringBuffer StringBuilder
Immutable Mutable mutable
String operations such as append would be less efficient String operations such as append would be more efficient, String operations such as append would be more efficient
– synchronized Not synchronized.
– versions 1.4 or below you’ll have to use StringBuffer. StringBuilder was introduced in Java 1.5

43) What are the advantage of using unicode characters ?
• Much larger number of characters or group of characters
• Contains some non western European characters
• Supported by all modern technologies
• Enhance integration opportunities
• Easy conversion from legacy code pages

44) Can you explain about literals in Java ?

Literals are used to represent a fixed value in source code. Literals don’t require computation. For Example, we will have a look at using literals to assign a value to an int variable.
int Days = 7;
45) Is it possible to override an overloaded method in Java ?
Yes. We can override an overloaded method if that method in not a static or final.

46) What is the maximum size of an int ?

-(2 power 31) to (2 power 31-1) or -2,147,483,648 to 2,147,483,647

47) Can you explain about autoboxing and unboxing in Java ?

When primitive data types are automatically converted into it’s wrapper type, it is called boxing. The opposite operation of converting wrapper class objects to it’s primitive type is known as unboxing.
ArrayList<Integer> list = new ArrayList<Integer>();
list.add(1); //autoboxing – primitive to object
int number = list.get(0); // unboxing

48) How to change the heap size of a JVM ?

The old generation’s default heap size can be overridden by using the -Xms and -Xmx switches to specify the initial and maximum sizes respectively:
Format – java -Xms <initial size> -Xmx <maximum size> program
Example – java -Xms64m -Xmx128m Myprogram
49) Is it possible to have multiple public classes in Java ?
As per java language specification, there can be only one public class in a file (.java) and file name should be same as public class name. If you want another class accessible in other places, you may create a separate java file.
50) What are Variable Arguments or varargs?
Variable Arguments allow calling a method with different number of parameters. Consider the example method sum below. This sum method can be called with 1 int parameter or 2 int parameters or more int parameters.
//int(type) followed … (three dot’s) is syntax of a variable argument.
public int sum(int… numbers) {
//inside the method a variable argument is similar to an array.
//number can be treated as if it is declared as int[] numbers;
int sum = 0;
for (int number: numbers) {
sum += number;
}
return sum;
}

public static void main(String[] args) {
VariableArgumentExamples example = new VariableArgumentExamples();
//3 Arguments
System.out.println(example.sum(1, 4, 5));//10
//4 Arguments
System.out.println(example.sum(1, 4, 5, 20));//30
//0 Arguments
System.out.println(example.sum());//0
}
51) What are Asserts used for?
Assertions are introduced in Java 1.4. They enable you to validate assumptions. If an assert fails (i.e. returns false), AssertionError is thrown (if assertions are enabled). Basic assert is shown in the example below
private int computerSimpleInterest(int principal,float interest,int years){
assert(principal>0);
return 100;
}
52) When should Asserts be used?
Assertions should not be used to validate input data to a public method or command line argument. IllegalArgumentException would be a better option. In public method, only use assertions to check for cases which are never supposed to happen.
53) What is Garbage Collection?
Garbage Collection is a name given to automatic memory management in Java. Aim of Garbage Collection is to Keep as much of heap available (free) for the program as possible. JVM removes objects on the heap which no longer have references from the heap.
54) Can you explain Garbage Collection with an example?
Let’s say the below method is called from a function.
void method(){
Calendar calendar = new GregorianCalendar(2000,10,30);
System.out.println(calendar);
}
An object of the class GregorianCalendar is created on the heap by the first line of the function with one reference variable calendar.
After the function ends execution, the reference variable calendar is no longer valid. Hence, there are no references to the object created in the method.
JVM recognizes this and removes the object from the heap. This is called Garbage Collection.
55) When is Garbage Collection run?
Garbage Collection runs at the whims and fancies of the JVM (it isn’t as bad as that). Possible situations when Garbage Collection might run are
• when available memory on the heap is low
• when cpu is free
56) What are best practices on Garbage Collection?
Programmatically, we can request (remember it’s just a request – Not an order) JVM to run Garbage Collection by calling System.gc() method.
JVM might throw an OutOfMemoryException when memory is full and no objects on the heap are eligible for garbage collection.
finalize() method on the objected is run before the object is removed from the heap from the garbage collector. We recommend not to write any code in finalize();
57) What are Initialization Blocks?
Initialization Blocks – Code which runs when an object is created or a class is loaded
There are two types of Initialization Blocks
Static Initializer: Code that runs when a class is loaded.
Instance Initializer: Code that runs when a new object is created.
58) What is a Static Initializer?
Look at the example below:Code within static{ and } is called a static initializer. This is run only when class is first loaded. Only static variables can be accessed in a static initializer. Even though three instances are created static initializer is run only once.
public class InitializerExamples {
static int count;
int i;

static{
//This is a static initializers. Run only when Class is first loaded.
//Only static variables can be accessed
System.out.println(“Static Initializer”);
//i = 6;//COMPILER ERROR
System.out.println(“Count when Static Initializer is run is ” + count);
}

public static void main(String[] args) {
InitializerExamples example = new InitializerExamples();
InitializerExamples example2 = new InitializerExamples();
InitializerExamples example3 = new InitializerExamples();
}
}
Example Output
Static Initializer
Count when Static Initializer is run is 0
59) What is an Instance Initializer Block?
Let’s look at an example : Code within instance initializer is run every time an instance of the class is created.
public class InitializerExamples {
static int count;
int i;
{
//This is an instance initializers. Run every time an object is created.
//static and instance variables can be accessed
System.out.println(“Instance Initializer”);
i = 6;
count = count + 1;
System.out.println(“Count when Instance Initializer is run is ” + count);
}

public static void main(String[] args) {
InitializerExamples example = new InitializerExamples();
InitializerExamples example1 = new InitializerExamples();
InitializerExamples example2 = new InitializerExamples();
}

}
Example Output

Instance Initializer
Count when Instance Initializer is run is 1
Instance Initializer
Count when Instance Initializer is run is 2
Instance Initializer
Count when Instance Initializer is run is 3

60) What are Regular Expressions?
Regular Expressions make parsing, scanning and splitting a string very easy. We will first look at how you can evaluate a regular expressions in Java – using Patter, Matcher and Scanner classes. We will then look into how to write a regular expression.
61) What is Tokenizing?
Tokenizing means splitting a string into several sub strings based on delimiters. For example, delimiter ; splits the string ac;bd;def;e into four sub strings ac, bd, def and e.
Delimiter can in itself be any of the regular expression(s) we looked at earlier.
String.split(regex) function takes regex as an argument.
62) Can you give an example of Tokenizing?
private static void tokenize(String string,String regex) {
String[] tokens = string.split(regex);
System.out.println(Arrays.toString(tokens));
}

tokenize(“ac;bd;def;e”,”;”);//[ac, bd, def, e]

63) How can you Tokenize using Scanner Class?
private static void tokenizeUsingScanner(String string,String regex) {
Scanner scanner = new Scanner(string);
scanner.useDelimiter(regex);
List<String> matches = new ArrayList<String>();
while(scanner.hasNext()){
matches.add(scanner.next());
}
System.out.println(matches);
}

tokenizeUsingScanner(“ac;bd;def;e”,”;”);//[ac, bd, def, e]
64) How do you add hours to a date object?
Lets now look at adding a few hours to a date object. All date manipulation to date needs to be done by adding milliseconds to the date. For example, if we want to add 6 hour, we convert 6 hours into millseconds. 6 hours = 6 * 60 * 60 * 1000 milliseconds. Below examples shows specific code.
Date date = new Date();

//Increase time by 6 hrs
date.setTime(date.getTime() + 6 * 60 * 60 * 1000);
System.out.println(date);

//Decrease time by 6 hrs
date = new Date();
date.setTime(date.getTime() – 6 * 60 * 60 * 1000);
System.out.println(date);