Java Interview Questions - Part 4 of 7

What is a native method?
A native method is a method that is implemented in a language other than Java.
---------------------------------------------------------------------------------------------------------------------

What are order of precedence and associativity, and how are they used?
Order of precedence determines the order in which operators are evaluated in expressions. Associatity determines whether an expression is evaluated left-to-right or right-to-left
---------------------------------------------------------------------------------------------------------------------

What is the catch or declare rule for method declarations?
If a checked exception may be thrown within the body of a method, the method must either catch the exception or declare it in its throws clause.
---------------------------------------------------------------------------------------------------------------------

Can an anonymous class be declared as implementing an interface and extending a class?
An anonymous class may implement an interface or extend a superclass, but may not be declared to do both.
---------------------------------------------------------------------------------------------------------------------

What is the range of the char type?
The range of the char type is 0 to 2^16 - 1.
----------------------------------------------------------------------------------------------------------------------

What is the purpose of finalization?
The purpose of finalization is to give an unreachable object the opportunity to perform any cleanup processing before the object is garbage collected.
---------------------------------------------------------------------------------------------------------------------

What is the difference between the Boolean & operator and the && operator?
If an expression involving the Boolean & operator is evaluated, both operands are evaluated. Then the & operator is applied to the operand. When an expression involving the && operator is evaluated, the first operand is evaluated. If the first operand returns a value of true then the second operand is evaluated. The && operator is then applied to the first and second operands. If the first operand evaluates to false, the evaluation of the second operand is skipped.
---------------------------------------------------------------------------------------------------------------------


Struts

What is Jakarta Struts Framework?
Jakarta Struts is open source implementation of MVC (Model-View-Controller) pattern for the development of web based applications. Jakarta Struts is robust architecture and can be used for the development of application of any size. Struts framework makes it much easier to design scalable, reliable Web applications with Java.
---------------------------------------------------------------------------------------------------------------------

What is ActionServlet?
The class org.apache.struts.action.ActionServlet is the called the ActionServlet. In the the Jakarta Struts Framework this class plays the role of controller. All the requests to the
---------------------------------------------------------------------------------------------------------------------

Can we use the constructor, instead of init(), to initialize servlet?
Yes , of course you can use the constructor instead of init(). There’s nothing to stop you. But you shouldn’t. The original reason for init() was that ancient versions of Java couldn’t dynamically invoke constructors with arguments, so there was no way to give the constructur a ServletConfig. That no longer applies, but servlet containers still will only call your no-arg constructor. So you won’t have access to a ServletConfig or ServletContext.
---------------------------------------------------------------------------------------------------------------------

How can a servlet refresh automatically if some new data has entered the database?
You can use a client-side Refresh or Server Push.
---------------------------------------------------------------------------------------------------------------------

EJB interview questions

Are enterprise beans allowed to use Thread.sleep()?
Enterprise beans make use of the services provided by the EJB container, such as life-cycle management. To avoid conflicts with these services, enterprise beans are restricted from performing certain operations: Managing or synchronizing threads
---------------------------------------------------------------------------------------------------------------------

Is is possible for an EJB client to marshal an object of class java.lang.Class to an EJB?
Technically yes, spec. compliant NO! - The enterprise bean must not attempt to query a class to obtain information about the declared members that are not otherwise accessible to the enterprise bean because of the security rules of the Java language.
---------------------------------------------------------------------------------------------------------------------

Is it legal to have static initializer blocks in EJB?
Although technically it is legal, static initializer blocks are used to execute some piece of code before executing any constructor or method while instantiating a class. Static initializer blocks are also typically used to initialize static fields - which may be illegal in EJB if they are read/write - In EJB this can be achieved by including the code in either the ejbCreate(), setSessionContext() or setEntityContext() methods.

Java Interview Questions - Part 4 of 7

What is a native method?
A native method is a method that is implemented in a language other than Java.
---------------------------------------------------------------------------------------------------------------------

What are order of precedence and associativity, and how are they used?
Order of precedence determines the order in which operators are evaluated in expressions. Associatity determines whether an expression is evaluated left-to-right or right-to-left
---------------------------------------------------------------------------------------------------------------------

What is the catch or declare rule for method declarations?
If a checked exception may be thrown within the body of a method, the method must either catch the exception or declare it in its throws clause.
---------------------------------------------------------------------------------------------------------------------

Can an anonymous class be declared as implementing an interface and extending a class?
An anonymous class may implement an interface or extend a superclass, but may not be declared to do both.
---------------------------------------------------------------------------------------------------------------------

What is the range of the char type?
The range of the char type is 0 to 2^16 - 1.
----------------------------------------------------------------------------------------------------------------------

What is the purpose of finalization?
The purpose of finalization is to give an unreachable object the opportunity to perform any cleanup processing before the object is garbage collected.
---------------------------------------------------------------------------------------------------------------------

What is the difference between the Boolean & operator and the && operator?
If an expression involving the Boolean & operator is evaluated, both operands are evaluated. Then the & operator is applied to the operand. When an expression involving the && operator is evaluated, the first operand is evaluated. If the first operand returns a value of true then the second operand is evaluated. The && operator is then applied to the first and second operands. If the first operand evaluates to false, the evaluation of the second operand is skipped.
---------------------------------------------------------------------------------------------------------------------


Struts

What is Jakarta Struts Framework?
Jakarta Struts is open source implementation of MVC (Model-View-Controller) pattern for the development of web based applications. Jakarta Struts is robust architecture and can be used for the development of application of any size. Struts framework makes it much easier to design scalable, reliable Web applications with Java.
---------------------------------------------------------------------------------------------------------------------

What is ActionServlet?
The class org.apache.struts.action.ActionServlet is the called the ActionServlet. In the the Jakarta Struts Framework this class plays the role of controller. All the requests to the
---------------------------------------------------------------------------------------------------------------------

Can we use the constructor, instead of init(), to initialize servlet?
Yes , of course you can use the constructor instead of init(). There’s nothing to stop you. But you shouldn’t. The original reason for init() was that ancient versions of Java couldn’t dynamically invoke constructors with arguments, so there was no way to give the constructur a ServletConfig. That no longer applies, but servlet containers still will only call your no-arg constructor. So you won’t have access to a ServletConfig or ServletContext.
---------------------------------------------------------------------------------------------------------------------

How can a servlet refresh automatically if some new data has entered the database?
You can use a client-side Refresh or Server Push.
---------------------------------------------------------------------------------------------------------------------

EJB interview questions

Are enterprise beans allowed to use Thread.sleep()?
Enterprise beans make use of the services provided by the EJB container, such as life-cycle management. To avoid conflicts with these services, enterprise beans are restricted from performing certain operations: Managing or synchronizing threads
---------------------------------------------------------------------------------------------------------------------

Is is possible for an EJB client to marshal an object of class java.lang.Class to an EJB?
Technically yes, spec. compliant NO! - The enterprise bean must not attempt to query a class to obtain information about the declared members that are not otherwise accessible to the enterprise bean because of the security rules of the Java language.
---------------------------------------------------------------------------------------------------------------------

Is it legal to have static initializer blocks in EJB?
Although technically it is legal, static initializer blocks are used to execute some piece of code before executing any constructor or method while instantiating a class. Static initializer blocks are also typically used to initialize static fields - which may be illegal in EJB if they are read/write - In EJB this can be achieved by including the code in either the ejbCreate(), setSessionContext() or setEntityContext() methods.

Java Interview Questions - Part 3 of 7

Difference between JRE/JVM/JDK?
Why do threads block on I/O? - Threads block on i/o (that is enters the waiting state) so that other threads may execute while the I/O operation is performed.

------------------------------------------------------------------------------------------------------------------------

What is synchronization and why is it important?
With respect to multithreading, synchronization is the capability to control the access of multiple threads to shared resources. Without synchronization, it is possible for one thread to modify a shared object while another thread is in the process of using or updating that object’s value. This often leads to significant errors.
--------------------------------------------------------------------------------------------------------------------------

Is null a keyword?
The null value is not a keyword.
--------------------------------------------------------------------------------------------------------------------------

Can there be an abstract class with no abstract methods in it?
Yes
--------------------------------------------------------------------------------------------------------------------------

Can an Interface be final?
No
--------------------------------------------------------------------------------------------------------------------------

Can an Interface have an inner class?
Yes.
--------------------------------------------------------------------------------------------------------------------------

Which characters may be used as the second character of an identifier,but not as the first character of an identifier?
The digits 0 through 9 may not be used as the first character of an identifier but they may be used after the first character of an identifier.

What modifiers may be used with an inner class that is a member of an outer class? - A (non-local) inner class may be declared as public, protected, private, static, final, or abstract.
-----------------------------------------------------------------------------------------------------------------------------

How many bits are used to represent Unicode, ASCII, UTF-16, and UTF-8 characters?
Unicode requires 16 bits and ASCII require 7 bits. Although the ASCII character set uses only 7 bits, it is usually represented as 8 bits. UTF-8 represents characters using 8, 16, and 18 bit patterns. UTF-16 uses 16-bit and larger bit patterns.
------------------------------------------------------------------------------------------------------------------------------

What are wrapped classes?
Wrapped classes are classes that allow primitive types to be accessed as objects.
-------------------------------------------------------------------------------------------------------------------------------

What restrictions are placed on the location of a package statement within a source code file?
A package statement must appear as the first line in a source code file (excluding blank lines and comments).
-------------------------------------------------------------------------------------------------------------------------------

What is the difference between preemptive scheduling and time slicing?
Under preemptive scheduling, the highest priority task executes until it enters the waiting or dead states or a higher priority task comes into existence. Under time slicing, a task executes for a predefined slice of time and then reenters the pool of ready tasks. The scheduler then determines which task should execute next, based on priority and other factors.

Java Interview Questions - Part 3 of 7

Difference between JRE/JVM/JDK?
Why do threads block on I/O? - Threads block on i/o (that is enters the waiting state) so that other threads may execute while the I/O operation is performed.

------------------------------------------------------------------------------------------------------------------------

What is synchronization and why is it important?
With respect to multithreading, synchronization is the capability to control the access of multiple threads to shared resources. Without synchronization, it is possible for one thread to modify a shared object while another thread is in the process of using or updating that object’s value. This often leads to significant errors.
--------------------------------------------------------------------------------------------------------------------------

Is null a keyword?
The null value is not a keyword.
--------------------------------------------------------------------------------------------------------------------------

Can there be an abstract class with no abstract methods in it?
Yes
--------------------------------------------------------------------------------------------------------------------------

Can an Interface be final?
No
--------------------------------------------------------------------------------------------------------------------------

Can an Interface have an inner class?
Yes.
--------------------------------------------------------------------------------------------------------------------------

Which characters may be used as the second character of an identifier,but not as the first character of an identifier?
The digits 0 through 9 may not be used as the first character of an identifier but they may be used after the first character of an identifier.

What modifiers may be used with an inner class that is a member of an outer class? - A (non-local) inner class may be declared as public, protected, private, static, final, or abstract.
-----------------------------------------------------------------------------------------------------------------------------

How many bits are used to represent Unicode, ASCII, UTF-16, and UTF-8 characters?
Unicode requires 16 bits and ASCII require 7 bits. Although the ASCII character set uses only 7 bits, it is usually represented as 8 bits. UTF-8 represents characters using 8, 16, and 18 bit patterns. UTF-16 uses 16-bit and larger bit patterns.
------------------------------------------------------------------------------------------------------------------------------

What are wrapped classes?
Wrapped classes are classes that allow primitive types to be accessed as objects.
-------------------------------------------------------------------------------------------------------------------------------

What restrictions are placed on the location of a package statement within a source code file?
A package statement must appear as the first line in a source code file (excluding blank lines and comments).
-------------------------------------------------------------------------------------------------------------------------------

What is the difference between preemptive scheduling and time slicing?
Under preemptive scheduling, the highest priority task executes until it enters the waiting or dead states or a higher priority task comes into existence. Under time slicing, a task executes for a predefined slice of time and then reenters the pool of ready tasks. The scheduler then determines which task should execute next, based on priority and other factors.

Java Interview Questions - Part 2 of 7

What are the different identifier states of a Thread?
The different identifiers of a Thread are: R - Running or runnable thread, S - Suspended thread, CW - Thread waiting on a condition variable, MW - Thread waiting on a monitor lock, MS - Thread suspended waiting on a monitor lock
------------------------------------------------------------------------------------------------------------------------

What are some alternatives to inheritance?
Delegation is an alternative to inheritance. Delegation means that you include an instance of another class as an instance variable, and forward messages to the instance. It is often safer than inheritance because it forces you to think about each message you forward, because the instance is of a known class, rather than a new class, and because it doesn’t force you to accept all the methods of the super class: you can provide only the methods that really make sense. On the other hand, it makes you write more code, and it is harder to re-use (because it is not a subclass).
---------------------------------------------------------------------------------------------------------------------------

Why isn’t there operator overloading?
Because C++ has proven by example that operator overloading makes code almost impossible to maintain. In fact there very nearly wasn’t even method overloading in Java, but it was thought that this was too useful for some very basic methods like print(). Note that some of the classes like DataOutputStream have unoverloaded methods like writeInt() and writeByte().
---------------------------------------------------------------------------------------------------------------------------

What does it mean that a method or field is “static"?
Static variables and methods are instantiated only once per class. In other words they are class variables, not instance variables. If you change the value of a static variable in a particular object, the value of that variable changes for all instances of that class. Static methods can be referenced with the name of the class rather than the name of a particular object of the class (though that works too). That’s how library methods like System.out.println() work. out is a static field in the java.lang.System class.
-----------------------------------------------------------------------------------------------------------------------------

How do I convert a numeric IP address like 192.18.97.39 into a hostname like java.sun.com?
String hostname = InetAddress.getByName("192.18.97.39").getHostName();

Java Interview Questions - Part 2 of 7

What are the different identifier states of a Thread?
The different identifiers of a Thread are: R - Running or runnable thread, S - Suspended thread, CW - Thread waiting on a condition variable, MW - Thread waiting on a monitor lock, MS - Thread suspended waiting on a monitor lock
------------------------------------------------------------------------------------------------------------------------

What are some alternatives to inheritance?
Delegation is an alternative to inheritance. Delegation means that you include an instance of another class as an instance variable, and forward messages to the instance. It is often safer than inheritance because it forces you to think about each message you forward, because the instance is of a known class, rather than a new class, and because it doesn’t force you to accept all the methods of the super class: you can provide only the methods that really make sense. On the other hand, it makes you write more code, and it is harder to re-use (because it is not a subclass).
---------------------------------------------------------------------------------------------------------------------------

Why isn’t there operator overloading?
Because C++ has proven by example that operator overloading makes code almost impossible to maintain. In fact there very nearly wasn’t even method overloading in Java, but it was thought that this was too useful for some very basic methods like print(). Note that some of the classes like DataOutputStream have unoverloaded methods like writeInt() and writeByte().
---------------------------------------------------------------------------------------------------------------------------

What does it mean that a method or field is “static"?
Static variables and methods are instantiated only once per class. In other words they are class variables, not instance variables. If you change the value of a static variable in a particular object, the value of that variable changes for all instances of that class. Static methods can be referenced with the name of the class rather than the name of a particular object of the class (though that works too). That’s how library methods like System.out.println() work. out is a static field in the java.lang.System class.
-----------------------------------------------------------------------------------------------------------------------------

How do I convert a numeric IP address like 192.18.97.39 into a hostname like java.sun.com?
String hostname = InetAddress.getByName("192.18.97.39").getHostName();

Java Interview Questions - Part 1 of 7

Can an Interface have an inner class? - Yes.
public interface abc
{
static int i=0; void dd();
class a1
{
a1()
{
int j;
System.out.println("inside");
};
public static void main(String a1[])
{
System.out.println("in interfia");
}
}
}
------------------------------------------------------------------------------------

Can we define private and protected modifiers for variables in interfaces?
No
-----------------------------------------------------------------------------------

What is Externalizable?
Externalizable is an Interface that extends Serializable Interface. And sends data into Streams in Compressed Format. It has two methods, writeExternal(ObjectOuput out) and readExternal(ObjectInput in)
-------------------------------------------------------------------------------------

What modifiers are allowed for methods in an Interface?
Only public and abstract modifiers are allowed for methods in interfaces.
--------------------------------------------------------------------------------------

What is a local, member and a class variable?
Variables declared within a method are “local” variables. Variables declared within the class i.e not within any methods are “member” variables (global variables). Variables declared within the class i.e not within any methods and are defined as “static” are class variables
----------------------------------------------------------------------------------------

posted by Dipali at 8:29 PM | 0 comments links to this post
Thursday, September 08, 2005

General Java Interview Questions
Core Java :
What is a virtual function in C++?
Simply put, the virtual keyword enables a function to be 'virtual' which then gives possibility for that function to be overridden (redefined) in one or more descendant classes. It is a good feature since the specific function to call is determined at run-time. In other words, a virtual function allows derived classes to replace the implementation provided by the base class.

--------------------------------------------------------------------------------

What is the difference between private, protected, and public?
These keywords are for allowing privilages to components such as functions and variables.
Public: accessible to all classes
Private: accessible only to the class to which they belong
Protected: accessible to the class to which they belong and any subclasses.

--------------------------------------------------------------------------------
What is a cartesian product in PL/SQL?
When a Join condition is not specified by the programmer or is invalid(fails), PL/SQL forms a Cartesian product.
In a Cartesian product, all combinations of rows will be displayed.
For example, All rows in the first table are joined to all rows in the second table. It joins a bunch of rows and it's result is rarely useful unless you have a need to combine all rows from all tables.
-------------------------------------------------------------------------------
What is mutual exclusion? How can you take care of mutual exclusion using Java threads?
Mutual exclusion is where no two processes can access critical regions of memory at the same time.
Java provides many utilities to deal with mutual exclusion with the use of threaded programming.
For mutual exclusion, you can simply use the synchronized keyword and explicitly or implicitly provide an Object, any Object, to synchronize on.
The runtime system/Java compiler takes care of the gruesome details for you. The synchronized keyword can be applied to a class, to a method, or to a block of code. There are several methods in Java used for communicating mutually exclusive threads such as wait( ), notify( ), or notifyAll( ). For example, the notifyAll( ) method wakes up all threads that are in the wait list of an object.
--------------------------------------------------------------------------------
What are some advantages and disadvantages of Java Sockets?
Some advantages of Java Sockets:

Sockets are flexible and sufficient. Efficient socket based programming can be easily implemented for general communications.


Sockets cause low network traffic. Unlike HTML forms and CGI scripts that generate and transfer whole web pages for each new request, Java applets can send only necessary updated information.

Some disadvantages of Java Sockets:

Security restrictions are sometimes overbearing because a Java applet running in a Web browser is only able to establish connections to the machine where it came from, and to nowhere else on the network

Despite all of the useful and helpful Java features, Socket based communications allows only to send packets of raw data between applications. Both the client-side and server-side have to provide mechanisms to make the data useful in any way.

Since the data formats and protocols remain application specific, the re-use of socket based implementations is limited.

What is the difference between an Interface and an Abstract class?
An Abstract class declares have at least one instance method that is declared abstract which will be implemented by the subclasses. An abstract class can have instance methods that implement a default behavior. An Interface can only declare constants and instance methods, but cannot implement default behavior.
--------------------------------------------------------------------------------
What is the purpose of garbage collection in Java, and when is it used?
The purpose of garbage collection is to identify and discard objects that are no longer needed by a program so that their resources can be reclaimed and reused. A Java object is subject to garbage collection when it becomes unreachable to the program in which it is used.
--------------------------------------------------------------------------------
Describe synchronization in respect to multithreading.?
With respect to multithreading, synchronization is the capability to control the access of multiple threads to shared resources. Without synchonization, it is possible for one thread to modify a shared variable while another thread is in the process of using or updating same shared variable. This usually leads to significant errors.
--------------------------------------------------------------------------------
Explain different way of using thread?
The thread could be implemented by using runnable interface or by inheriting from the Thread class. The former is more advantageous, 'cause when you are going for multiple inheritance..the only interface can help.
--------------------------------------------------------------------------------
What are pass by reference and passby value?
Pass By Reference means the passing the address itself rather than passing the value. Passby Value means passing a copy of the value to be passed.
--------------------------------------------------------------------------------
What is HashMap and Map?
Map is Interface and Hashmap is class that implements that.
--------------------------------------------------------------------------------
Difference between HashMap and HashTable?
The HashMap class is roughly equivalent to Hashtable, except that it is unsynchronized and permits nulls. (HashMap allows null values as key and value whereas Hashtable doesnt allow). HashMap does not guarantee that the order of the map will remain constant over time. HashMap is non synchronized and Hashtable is synchronized.
--------------------------------------------------------------------------------
Difference between Vector and ArrayList?
Vector is synchronized whereas arraylist is not.
--------------------------------------------------------------------------------
Difference between Swing and Awt?
AWT are heavy-weight componenets. Swings are light-weight components. Hence swing works faster than AWT.
--------------------------------------------------------------------------------
What is the difference between a constructor and a method?
A constructor is a member function of a class that is used to create objects of that class. It has the same name as the class itself, has no return type, and is invoked using the new operator. A method is an ordinary member function of a class. It has its own name, a return type (which may be void), and is invoked using the dot operator.
--------------------------------------------------------------------------------
What is an Iterators?
Some of the collection classes provide traversal of their contents via a java.util.Iterator interface. This interface allows you to walk a collection of objects, operating on each object in turn. Remember when using Iterators that they contain a snapshot of the collection at the time the Iterator was obtained; generally it is not advisable to modify the collection itself while traversing an Iterator.
--------------------------------------------------------------------------------
State the significance of public, private, protected, default modifiers both singly and in combination and state the effect of package relationships on declared items qualified by these modifiers.?
public : Public class is visible in other packages, field is visible everywhere (class must be public too) private : Private variables or methods may be used only by an instance of the same class that declares the variable or method, A private feature may only be accessed by the class that owns the feature. protected : Is available to all classes in the same package and also available to all subclasses of the class that owns the protected feature.This access is provided even to subclasses that reside in a different package from the class that owns the protected feature. default :What you get by default ie, without any access modifier (ie, public private or protected).It means that it is visible to all within a particular package.
--------------------------------------------------------------------------------
What is an abstract class?
Abstract class must be extended/subclassed (to be useful). It serves as a template. A class that is abstract may not be instantiated (ie, you may not call its constructor), abstract class may contain static data. Any class with an abstract method is automatically abstract itself, and must be declared as such. A class may be declared abstract even if it has no abstract methods. This prevents it from being instantiated.
--------------------------------------------------------------------------------
What is static in java?
Static means one per class, not one for each object no matter how many instance of a class might exist. This means that you can use them without creating an instance of a class.Static methods are implicitly final, because overriding is done based on the type of the object, and static methods are attached to a class, not an object. A static method in a superclass can be shadowed by another static method in a subclass, as long as the original method was not declared final. However, you can't override a static method with a nonstatic method. In other words, you can't change a static method into an instance method in a subclass.

---------------------------------------------------------------------------------
What is final?
A final class can't be extended ie., final class may not be subclassed. A final method can't be overridden when its class is inherited. You can't change value of a final variable (is a constant).
--------------------------------------------------------------------------------
Are the imports checked for validity at compile time? e.g. will the code containing an import such as java.lang.ABCD compile?
Yes the imports are checked for the semantic validity at compile time. The code containing above line of import will not compile. It will throw an error saying,can not resolve symbol symbol : class ABCD location: package io import java.io.ABCD;
--------------------------------------------------------------------------------
Does importing a package imports the subpackages as well?
e.g. Does importing com.MyTest.* also import com.MyTest.UnitTests.*?
No you will have to import the subpackages explicitly. Importing com.MyTest.* will import classes in the package MyTest only. It will not import any class in any of it's subpackage.
--------------------------------------------------------------------------------
What is the difference between declaring a variable and defining a variable?
In declaration we just mention the type of the variable and it's name. We do not initialize it. But defining means declaration + initialization. e.g String s; is just a declaration while String s = new String ("abcd"); Or String s = "abcd"; are both definitions.
--------------------------------------------------------------------------------
What is the default value of an object reference declared as an instance variable?
null unless we define it explicitly.
--------------------------------------------------------------------------------
Can a level class be private or protected?
No. A level class can not be private or protected. It can have either "public" or no modifier. If it does not have a modifier it is supposed to have a default access.If a level class is declared as private the compiler will complain that the "modifier private is not allowed here". This means that a level class can not be private. Same is the case with protected.
--------------------------------------------------------------------------------
What type of parameter passing does Java support?
In Java the arguments are always passed by value .
--------------------------------------------------------------------------------
Primitive data types are passed by reference or pass by value?
Primitive data types are passed by value.
--------------------------------------------------------------------------------
Objects are passed by value or by reference?
Java only supports pass by value. With objects, the object reference itself is passed by value and so both the original reference and parameter copy both refer to the same object .
--------------------------------------------------------------------------------
What is serialization?
Serialization is a mechanism by which you can save the state of an object by converting it to a byte stream.
--------------------------------------------------------------------------------
How do I serialize an object to a file?
The class whose instances are to be serialized should implement an interface Serializable. Then you pass the instance to the ObjectOutputStream which is connected to a fileoutputstream. This will save the object to a file.
--------------------------------------------------------------------------------
Which methods of Serializable interface should I implement?
The serializable interface is an empty interface, it does not contain any methods. So we do not implement any methods.
--------------------------------------------------------------------------------
How can I customize the seralization process?
i.e. how can one have a control over the serialization process?
Yes it is possible to have control over serialization process. The class should implement Externalizable interface. This interface contains two methods namely readExternal and writeExternal. You should implement these methods and write the logic for customizing the serialization process.
--------------------------------------------------------------------------------
What is an abstract class?
Abstract class must be extended/subclassed (to be useful). It serves as a template. A class that is abstract may not be instantiated (ie, you may not call its constructor), abstract class may contain static data. Any class with an abstract method is automatically abstract itself, and must be declared as such. A class may be declared abstract even if it has no abstract methods. This prevents it from being instantiated.
---------------------------------------------------------------------------------
What is the common usage of serialization?
Whenever an object is to be sent over the network, objects need to be serialized. Moreover if the state of an object is to be saved, objects need to be serilazed.
-------------------------------------------------------------------------------
What is Externalizable interface?
Externalizable is an interface which contains two methods readExternal and writeExternal. These methods give you a control over the serialization mechanism. Thus if your class implements this interface, you can customize the serialization process by implementing these methods.
--------------------------------------------------------------------------------
What happens to the object references included in the object?
The serialization mechanism generates an object graph for serialization. Thus it determines whether the included object references are serializable or not. This is a recursive process. Thus when an object is serialized, all the included objects are also serialized alongwith the original obect.
--------------------------------------------------------------------------------
What one should take care of while serializing the object?
One should make sure that all the included objects are also serializable. If any of the objects is not serializable then it throws a NotSerializableException.
--------------------------------------------------------------------------------
What if the main method is declared as private?
The program compiles properly but at runtime it will give "Main method not public." message.
--------------------------------------------------------------------------------
What if the static modifier is removed from the signature of the main method?
Program compiles. But at runtime throws an error "NoSuchMethodError".
--------------------------------------------------------------------------------
What if I write static public void instead of public static void?
Program compiles and runs properly.
--------------------------------------------------------------------------------
What if I do not provide the String array as the argument to the method?
Program compiles but throws a runtime error "NoSuchMethodError".
--------------------------------------------------------------------------------
What is the first argument of the String array in main method?
The String array is empty. It does not have any element. This is unlike C/C++ where the first element by default is the program name.
--------------------------------------------------------------------------------
If I do not provide any arguments on the command line, then the String array of Main method will be empty of null?
It is empty. But not null.
--------------------------------------------------------------------------------
How can one prove that the array is not null but empty?
Print args.length. It will print 0. That means it is empty. But if it would have been null then it would have thrown a NullPointerException on attempting to print args.length.
--------------------------------------------------------------------------------
What environment variables do I need to set on my machine in order to be able to run Java programs?
CLASSPATH and PATH are the two variables.
--------------------------------------------------------------------------------
Can an application have multiple classes having main method?
Yes it is possible. While starting the application we mention the class name to be run. The JVM will look for the Main method only in the class whose name you have mentioned. Hence there is not conflict amongst the multiple classes having main method.
--------------------------------------------------------------------------------
Can I have multiple main methods in the same class?
No the program fails to compile. The compiler says that the main method is already defined in the class.
--------------------------------------------------------------------------------
Do I need to import java.lang package any time? Why ?
No. It is by default loaded internally by the JVM.
--------------------------------------------------------------------------------
Can I import same package/class twice?
Will the JVM load the package twice at runtime?
One can import the same package or same class multiple times. Neither compiler nor JVM complains abt it. And the JVM will internally load the class only once no matter how many times you import the same class.
--------------------------------------------------------------------------------
What are Checked and UnChecked Exception?
A checked exception is some subclass of Exception (or Exception itself), excluding class RuntimeException and its subclasses. Making an exception checked forces client programmers to deal with the possibility that the exception will be thrown. eg, IOException thrown by java.io.FileInputStream's read() method
----------------------------------------------------------------------------------
checked exceptions are RuntimeException and any of its subclasses. Class Error and its subclasses also are unchecked. With an unchecked exception, however, the compiler doesn't force client programmers either to catch the exception or declare it in a throws clause. In fact, client programmers may not even know that the exception could be thrown. eg, StringIndexOutOfBoundsException thrown by String's charAt() method Checked exceptions must be caught at compile time. Runtime exceptions do not need to be. Errors often cannot be.
--------------------------------------------------------------------------------
What is Overriding?
When a class defines a method using the same name, return type, and arguments as a method in its superclass, the method in the class overrides the method in the superclass. When the method is invoked for an object of the class, it is the new definition of the method that is called, and not the method definition from superclass. Methods may be overridden to be more public, not more private.
-------------------------------------------------------------------------------
What are different types of inner classes?
They are
Nested -level classes, Member classes, Local classes, Anonymous classes

Nested -level classes- If you declare a class within a class and specify the static modifier, the compiler treats the class just like any other -level class. Any class outside the declaring class accesses the nested class with the declaring class name acting similarly to a package. eg, outer.inner. -level inner classes implicitly have access only to static variables.There can also be inner interfaces. All of these are of the nested -level variety.

Member classes - Member inner classes are just like other member methods and member variables and access to the member class is restricted, just like methods and variables. This means a public member class acts similarly to a nested -level class. The primary difference between member classes and nested -level classes is that member classes have access to the specific instance of the enclosing class.

Local classes - Local classes are like local variables, specific to a block of code. Their visibility is only within the block of their declaration. In order for the class to be useful beyond the declaration block, it would need to implement a more publicly available interface.Because local classes are not members, the modifiers public, protected, private, and static are not usable.

Anonymous classes - Anonymous inner classes extend local inner classes one level further. As anonymous classes have no name, you cannot provide a constructor.

-----------------------------------------------------------------------------------
Are the imports checked for validity at compile time? e.g. will the code containing an import such as java.lang.ABCD compile?
Yes the imports are checked for the semantic validity at compile time. The code containing above line of import will not compile. It will throw an error saying,can not resolve symbol symbol : class ABCD location: package io import java.io.ABCD;
--------------------------------------------------------------------------------
Does importing a package imports the subpackages as well? e.g. Does importing com.MyTest.* also import com.MyTest.UnitTests.*?
No you will have to import the subpackages explicitly. Importing com.MyTest.* will import classes in the package MyTest only. It will not import any class in any of it's subpackage.
-------------------------------------------------------------------------------
What is the difference between declaring a variable and defining a variable?
In declaration we just mention the type of the variable and it's name. We do not initialize it. But defining means declaration + initialization. e.g String s; is just a declaration while String s = new String ("abcd"); Or String s = "abcd"; are both definitions.
--------------------------------------------------------------------------------
What is the default value of an object reference declared as an instance variable?
null unless we define it explicitly.
--------------------------------------------------------------------------------
Can a level class be private or protected?
No. A level class can not be private or protected. It can have either "public" or no modifier. If it does not have a modifier it is supposed to have a default access.If a level class is declared as private the compiler will complain that the "modifier private is not allowed here". This means that a level class can not be private. Same is the case with protected.
--------------------------------------------------------------------------------
What type of parameter passing does Java support?
In Java the arguments are always passed by value .
--------------------------------------------------------------------------------
Primitive data types are passed by reference or pass by value?
Primitive data types are passed by value.
--------------------------------------------------------------------------------
Objects are passed by value or by reference?
Java only supports pass by value. With objects, the object reference itself is passed by value and so both the original reference and parameter copy both refer to the same object .
--------------------------------------------------------------------------------
What is serialization?
Serialization is a mechanism by which you can save the state of an object by converting it to a byte stream.
--------------------------------------------------------------------------------
How do I serialize an object to a file?
The class whose instances are to be serialized should implement an interface Serializable. Then you pass the instance to the ObjectOutputStream which is connected to a fileoutputstream. This will save the object to a file.
--------------------------------------------------------------------------------
Which methods of Serializable interface should I implement?
The serializable interface is an empty interface, it does not contain any methods. So we do not implement any methods.
--------------------------------------------------------------------------------
How can I customize the seralization process?
i.e. how can one have a control over the serialization process?
Yes it is possible to have control over serialization process. The class should implement Externalizable interface. This interface contains two methods namely readExternal and writeExternal. You should implement these methods and write the logic for customizing the serialization process.
--------------------------------------------------------------------------------
What is the common usage of serialization?
Whenever an object is to be sent over the network, objects need to be serialized. Moreover if the state of an object is to be saved, objects need to be serilazed.
--------------------------------------------------------------------------------
What is Externalizable interface?
Externalizable is an interface which contains two methods readExternal and writeExternal. These methods give you a control over the serialization mechanism. Thus if your class implements this interface, you can customize the serialization process by implementing these methods.
--------------------------------------------------------------------------------
What happens to the object references included in the object?
The serialization mechanism generates an object graph for serialization. Thus it determines whether the included object references are serializable or not. This is a recursive process. Thus when an object is serialized, all the included objects are also serialized alongwith the original obect.
--------------------------------------------------------------------------------
What one should take care of while serializing the object?
One should make sure that all the included objects are also serializable. If any of the objects is not serializable then it throws a NotSerializableException.
--------------------------------------------------------------------------------
What happens to the static fields of a class during serialization?
Are these fields serialized as a part of each serialized object?
Yes the static fields do get serialized. If the static field is an object then it must have implemented Serializable interface. The static fields are serialized as a part of every object. But the commonness of the static fields across all the instances is maintained even after serialization.
--------------------------------------------------------------------------------
How are Observer and Observable used?
Objects that subclass the Observable class maintain a list of observers. When an Observable object is updated it invokes the update() method of each of its observers to notify the observers that it has changed state. The Observer interface is implemented by objects that observe Observable objects. [Received from Venkateswara Manam]
--------------------------------------------------------------------------------
What is synchronization and why is it important?
With respect to multithreading, synchronization is the capability to control the access of multiple threads to shared resources. Without synchronization, it is possible for one thread to modify a shared object while another thread is in the process of using or updating that object's value. This often leads to significant errors.
--------------------------------------------------------------------------------
How does Java handle integer overflows and underflows?
It uses those low order bytes of the result that can fit into the size of the type allowed by the operation.
--------------------------------------------------------------------------------
Does garbage collection guarantee that a program will not run out of memory?
Garbage collection does not guarantee that a program will not run out of memory. It is possible for programs to use up memory resources faster than they are garbage collected. It is also possible for programs to create objects that are not subject to garbage collection .
--------------------------------------------------------------------------------
What is the difference between preemptive scheduling and time slicing?
Under preemptive scheduling, the highest priority task executes until it enters the waiting or dead states or a higher priority task comes into existence. Under time slicing, a task executes for a predefined slice of time and then reenters the pool of ready tasks. The scheduler then determines which task should execute next, based on priority and other factors.
--------------------------------------------------------------------------------
When a thread is created and started, what is its initial state?
A thread is in the ready state after it has been created and started.
--------------------------------------------------------------------------------
What is the purpose of finalization?
The purpose of finalization is to give an unreachable object the opportunity to perform any cleanup processing before the object is garbage collected.
--------------------------------------------------------------------------------
What is the Locale class?
The Locale class is used to tailor program output to the conventions of a particular geographic, political, or cultural region.
--------------------------------------------------------------------------------
What is the difference between a while statement and a do statement?
A while statement checks at the beginning of a loop to see whether the next loop iteration should occur. A do statement checks at the end of a loop to see whether the next iteration of a loop should occur. The do statement will always execute the body of a loop at least once.
--------------------------------------------------------------------------------
What is the difference between static and non-static variables?
A static variable is associated with the class as a whole rather than with specific instances of a class. Non-static variables take on unique values with each object instance.
--------------------------------------------------------------------------------
How are this() and super() used with constructors?
this() is used to invoke a constructor of the same class. super() is used to invoke a superclass constructor.
-------------------------------------------------------------------------------
Servlets:


Explain the life cycle methods of a Servlet.
The javax.servlet.Servlet interface defines the three methods known as life-cycle method. public void init(ServletConfig config) throws ServletException public void service( ServletRequest req, ServletResponse res) throws ServletException, IOException public void destroy() First the servlet is constructed, then initialized wih the init() method. Any request from client are handled initially by the service() method before delegating to the doXxx() methods in the case of HttpServlet. The servlet is removed from service, destroyed with the destroy() methid, then garbaged collected and finalized.
--------------------------------------------------------------------------------
What is the difference between the getRequestDispatcher(String path) method of javax.servlet.ServletRequest interface and javax.servlet.ServletContext interface?
The getRequestDispatcher(String path) method of javax.servlet.ServletRequest interface accepts parameter the path to the resource to be included or forwarded to, which can be relative to the request of the calling servlet. If the path begins with a "/" it is interpreted as relative to the current context root.
The getRequestDispatcher(String path) method of javax.servlet.ServletContext interface cannot accepts relative paths. All path must sart with a "/" and are interpreted as relative to curent context root.
--------------------------------------------------------------------------------
Explain the directory structure of a web application.
The directory structure of a web application consists of two parts. A private directory called WEB-INF A public resource directory which contains public resource folder. WEB-INF folder consists of 1. web.xml
2. classes directory
3. lib directory
--------------------------------------------------------------------------------
What are the common mechanisms used for session tracking?
Cookies SSL sessions URL- rewriting
--------------------------------------------------------------------------------
Explain ServletContext.
ServletContext interface is a window for a servlet to view it's environment. A servlet can use this interface to get information such as initialization parameters for the web applicationor servlet container's version. Every web application has one and only one ServletContext and is accessible to all active resource of that application.
--------------------------------------------------------------------------------
What is preinitialization of a servlet?
A container doesnot initialize the servlets ass soon as it starts up, it initializes a servlet when it receives a request for that servlet first time. This is called lazy loading. The servlet specification defines the element, which can be specified in the deployment descriptor to make the servlet container load and initialize the servlet as soon as it starts up. The process of loading a servlet before any request comes in is called preloading or preinitializing a servlet.
--------------------------------------------------------------------------------
What is the difference between Difference between doGet() and doPost()?
A doGet() method is limited with 2k of data to be sent, and doPost() method doesn't have this limitation. A request string for doGet() looks like the following: http://www.allapplabs.com/svt1?p1=v1&p2=v2&...&pN=vN


doPost() method call doesn't need a long text tail after a servlet name in a request. All parameters are stored in a request itself, not in a request string, and it's impossible to guess the data transmitted to a servlet only looking at a request string.
--------------------------------------------------------------------------------
What is the difference between HttpServlet and GenericServlet?
A GenericServlet has a service() method aimed to handle requests.
HttpServlet extends GenericServlet and adds support for doGet(), doPost(), doHead() methods (HTTP 1.0) plus doPut(), doOptions(), doDelete(), doTrace() methods (HTTP 1.1). Both these classes are abstract.
---------------------------------------------------------------------------------
JSP:
What is a output comment?
A comment that is sent to the client in the viewable page source.The JSP engine handles an output comment as uninterpreted HTML text, returning the comment in the HTML output sent to the client. You can see the comment by viewing the page source from your Web browser. JSP Syntax Example 1 Displays in the page source:
--------------------------------------------------------------------------------
What is a Hidden Comment?
A comments that documents the JSP page but is not sent to the client. The JSP engine ignores a hidden comment, and does not process any code within hidden comment tags. A hidden comment is not sent to the client, either in the displayed JSP page or the HTML page source. The hidden comment is useful when you want to hide or "comment out" part of your JSP page. You can use any characters in the body of the comment except the closing --%> combination. If you need to use --%> in your comment, you can escape it by typing --%\>. JSP Syntax Examples
--------------------------------------------------------------------------------
What is a _Expression?
An _expression tag contains a scripting language _expression that is evaluated, converted to a String, and inserted where the _expression appears in the JSP file. Because the value of an _expression is converted to a String, you can use an _expression within text in a JSP file. Like You cannot use a semicolon to end an _expression
--------------------------------------------------------------------------------
What is a Declaration?
A declaration declares one or more variables or methods for use later in the JSP source file. A declaration must contain at least one complete declarative statement. You can declare any number of variables or methods within one declaration tag, as long as they are separated by semicolons. The declaration must be valid in the scripting language used in the JSP file.
--------------------------------------------------------------------------------
What is a Scriptlet?
A scriptlet can contain any number of language statements, variable or method declarations, or expressions that are valid in the page scripting language.Within scriptlet tags, you can

1.Declare variables or methods to use later in the file (see also Declaration).

2.Write expressions valid in the page scripting language (see also _Expression).

3.Use any of the JSP implicit objects or any object declared with a tag.

You must write plain text, HTML-encoded text, or other JSP tags outside the scriptlet. Scriptlets are executed at request time, when the JSP engine processes the client request. If the scriptlet produces output, the output is stored in the out object, from which you can display it.
--------------------------------------------------------------------------------
What are implicit objects? List them?
Certain objects that are available for the use in JSP documents without being declared first. These objects are parsed by the JSP engine and inserted into the generated servlet. The implicit objects re listed below request response pageContext session application out config page exception
--------------------------------------------------------------------------------
Difference between forward and sendRedirect?
When you invoke a forward request, the request is sent to another resource on the server, without the client being informed that a different resource is going to process the request. This process occurs completly with in the web container. When a sendRedirtect method is invoked, it causes the web container to return to the browser indicating that a new URL should be requested. Because the browser issues a completly new request any object that are stored as request attributes before the redirect occurs will be lost. This extra round trip a redirect is slower than forward.
--------------------------------------------------------------------------------
What are the different scope valiues for the ?
The different scope values for are
1. page
2. request
3.session
4.application
--------------------------------------------------------------------------------
Explain the life-cycle mehtods in JSP?
THe generated servlet class for a JSP page implements the HttpJspPage interface of the javax.servlet.jsp package. Hte HttpJspPage interface extends the JspPage interface which inturn extends the Servlet interface of the javax.servlet package. the generated servlet class thus implements all the methods of the these three interfaces.

The JspPage interface declares only two mehtods - jspInit() and jspDestroy() that must be implemented by all JSP pages regardless of the client-server protocol.

However the JSP specification has provided the HttpJspPage interfaec specifically for the JSp pages serving HTTP requests.
This interface declares one method _jspService(). The jspInit()- The container calls the jspInit() to initialize te servlet instance.It is called before any other method, and is called only once for a servlet instance.
The _jspservice()- The container calls the _jspservice() for each request, passing it the request and the response objects.
The jspDestroy()- The container calls this when it decides take the instance out of service. It is the last method called n the servlet instance.

posted by Arpan The Progress at 12:17 AM 0 comments
C++

C++ Interview Questions

Is it possible to have Virtual Constructor? If yes, how?If not, Why not possible ?
There is nothing like Virtual Constructor.
The Constructor cant be virtual as the constructor is a code which is responsible for creating a instance of a class and it cant be delegated to any other object by virtual keyword means.
--------------------------------------------------------------------------------
What about Virtual Destructor?
Yes there is a Virtual Destructor. A destructor can be virtual as it is possible as at runtime depending on the type of object baller is balling to , proper destructor will be called.
--------------------------------------------------------------------------------
What is Pure Virtual Function? Why and when it is used ?
The abstract class whose pure virtual method has to be implemented by all the classes which derive on these. Otherwise it would result in a compilation error.
This construct should be used when one wants to ensure that all the derived classes implement the method defined as pure virtual in base class.
--------------------------------------------------------------------------------
What is problem with Runtime type identification?
The run time type identification comes at a cost of performance penalty. Compiler maintains the class.
--------------------------------------------------------------------------------
How Virtual functions call up is maintained?
Through Look up tables added by the compile to every class image. This also leads to performance penalty.
--------------------------------------------------------------------------------
Can inline functions have a recursion?
No.
Syntax wise It is allowed. But then the function is no longer Inline. As the compiler will never know how deep the recursion is at compilation time.
--------------------------------------------------------------------------------
How do you link a C++ program to C functions?
By using the extern "C" linkage specification around the C function declarations.
Programmers should know about mangled function names and type-safe linkages. Then they should explain how the extern "C" linkage specification statement turns that feature off during compilation so that the linker properly links function calls to C functions.
--------------------------------------------------------------------------------
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.
--------------------------------------------------------------------------------
How many ways are there to initialize an int with a constant?
1. int foo = 123;
2. int bar(123);
-------------------------------------------------------------------------------
What is your reaction to this line of code? delete this;
It is not a good programming Practice.
A good programmer will insist that you should absolutely never use the statement if the class is to be used by other programmers and instantiated as static, extern, or automatic objects. That much should be obvious.
The code has two built-in pitfalls. First, if it executes in a member function for an extern, static, or automatic object, the program will probably crash as soon as the delete statement executes. There is no portable way for an object to tell that it was instantiated on the heap, so the class cannot assert that its object is properly instantiated. Second, when an object commits suicide this way, the using program might not know about its demise. As far as the instantiating program is concerned, the object remains in scope and continues to exist even though the object did itself in. Subsequent dereferencing of the baller can and usually does lead to disaster. I think that the language rules should disallow the idiom, but that's another matter.
--------------------------------------------------------------------------------
What is the difference between a copy constructor and an overloaded assignment operator?
A copy constructor constructs a new object by using the content of the argument object. An overloaded assignment operator assigns the contents of an existing object to another existing object of the same class.
--------------------------------------------------------------------------------
When should you use multiple inheritance?
There are three acceptable answers:- "Never," "Rarely," and "When the problem domain cannot be accurately modeled any other way."
Consider an Asset class, Building class, Vehicle class, and CompanyCar class. All company cars are vehicles. Some company cars are assets because the organizations own them. Others might be leased. Not all assets are vehicles. Money accounts are assets. Real estate holdings are assets. Some real estate holdings are buildings. Not all buildings are assets. Ad infinitum. When you diagram these relationships, it becomes apparent that multiple inheritance is a likely and intuitive way to model this common problem domain. The applicant should understand, however, that multiple inheritance, like a chainsaw, is a useful tool that has its perils, needs respect, and is best avoided except when nothing else will do.
--------------------------------------------------------------------------------
What is a virtual destructor?
The simple answer is that a virtual destructor is one that is declared with the virtual attribute.
The behavior of a virtual destructor is what is important. If you destroy an object through a baller or reference to a base class, and the base-class destructor is not virtual, the derived-class destructors are not executed, and the destruction might not be comple
--------------------------------------------------------------------------------
Can a constructor throw a exception? How to handle the error when the constructor fails?
The constructor never throws a error.
--------------------------------------------------------------------------------
What are the debugging methods you use when came across a problem?
Debugging with tools like :
GDB, DBG, Forte, Visual Studio.

Analyzing the Core dump.

Using tusc to trace the last system call before crash.

Putting Debug statements in the program source code.
--------------------------------------------------------------------------------
How the compilers arranges the various sections in the executable image?
The executable had following sections:-
Data Section (uninitialized data variable section, initialized data variable section )
Code Section
Remember that all static variables are allocated in the initialized variable section.
--------------------------------------------------------------------------------
Explain the ISA and HASA class relationships. How would you implement each in a class design?
A specialized class "is" a specialization of another class and, therefore, has the ISA relationship with the other class.
This relationship is best implemented by embedding an object of the Salary class in the Employee class.
-------------------------------------------------------------------------------
When is a template a better solution than a base class?
When you are designing a generic class to contain or otherwise manage objects of other types, when the format and behavior of those other types are unimportant to their containment or management, and particularly when those other types are unknown (thus, the generality) to the designer of the container or manager class.
--------------------------------------------------------------------------------
What are the differences between a C++ struct and C++ class?
The default member and base-class access specifies are different.
This is one of the commonly misunderstood aspects of C++. Believe it or not, many programmers think that a C++ struct is just like a C struct, while a C++ class has inheritance, access specifies, member functions, overloaded operators, and so on. Actually, the C++ struct has all the features of the class. The only differences are that a struct defaults to public member access and public base-class inheritance, and a class defaults to the private access specified and private base-class inheritance.
--------------------------------------------------------------------------------
How do you know that your class needs a virtual destructor?
If your class has at least one virtual function, you should make a destructor for this class virtual. This will allow you to delete a dynamic object through a baller to a base class object. If the destructor is non-virtual, then wrong destructor will be invoked during deletion of the dynamic object.
--------------------------------------------------------------------------------
What is the difference between new/delete and malloc/free?
Malloc/free do not know about constructors and destructors. New and delete create and destroy objects, while malloc and free allocate and deallocate memory.
--------------------------------------------------------------------------------
What happens when a function throws an exception that was not specified by an exception specification for this function?
Unexpected() is called, which, by default, will eventually trigger abort().
--------------------------------------------------------------------------------
Can you think of a situation where your program would crash without reaching the breakball, which you set at the beginning of main()?
C++ allows for dynamic initialization of global variables before main() is invoked. It is possible that initialization of global will invoke some function. If this function crashes the crash will occur before main() is entered.
--------------------------------------------------------------------------------
What issue do auto_ptr objects address?
If you use auto_ptr objects you would not have to be concerned with heap objects not being deleted even if the exception is thrown.
--------------------------------------------------------------------------------
Is there any problem with the following:
char *a=NULL; char& p = *a;?
The result is undefined. You should never do this. A reference must always refer to some object.
--------------------------------------------------------------------------------
Why do C++ compilers need name mangling?
Name mangling is the rule according to which C++ changes function's name into function signature before passing that function to a linker. This is how the linker differentiates between different functions with the same name.
--------------------------------------------------------------------------------
What is Polymorphism?
'Polymorphism' is an object oriented term. Polymorphism may be defined as the ability of related objects to respond to the same message with different, but appropriate actions. In other words, polymorphism means taking more than one form. Polymorphism leads to two important aspects in Object Oriented terminology - Function Overloading and Function Overriding. Overloading is the practice of supplying more than one definition for a given function name in the same scope. The compiler is left to pick the appropriate version of the function or operator based on the arguments with which it is called. Overriding refers to the modifications made in the sub class to the inherited methods from the base class to change their behaviour.
--------------------------------------------------------------------------------
What is Operator overloading?
When an operator is overloaded, it takes on an additional meaning relative to a certain class. But it can still retain all of its old meanings.
Examples:
1) The operators >> and << may be used for I/O operations because in the header, they are overloaded.
2) In a stack class it is possible to overload the + operattor so that it appends the contents of one stack to the contents of another. But the + operator still retains its original meaning relative to other types of data.
--------------------------------------------------------------------------------
What is the difference between run time binding and compile time binding?
Dynamic Binding :
The address of the functions are determined at runtime rather than @ compile time. This is also known as "Late Binding".

Static Binding :
The address of the functions are determined at compile time rather than @ run time. This is also known as "Early Binding"
--------------------------------------------------------------------------------
When constructing an XML DTD, how do you create an external entity reference in an attribute value?

Every interview session should have at least one trick question. Although possible when using SGML, XML DTDs don't support defining external entity references in attribute values. It's more important for the candidate to respond to this question in a logical way than than the candidate know the somewhat obscure answer.
--------------------------------------------------------------------------------
How would you build a search engine for large volumes of XML data?
The way candidates answer this question may provide insight into their view of XML data. For those who view XML primarily as a way to denote structure for text files, a common answer is to build a full-text search and handle the data similarly to the way Internet portals handle HTML pages. Others consider XML as a standard way of transferring structured data between disparate systems. These candidates often describe some scheme of importing XML into a relational or object database and relying on the database's engine for searching. Lastly, candidates that have worked with vendors specializing in this area often say that the best way the handle this situation is to use a third party software package optimized for XML data.

Java Interview Questions - Part 1 of 7

Can an Interface have an inner class? - Yes.
public interface abc
{
static int i=0; void dd();
class a1
{
a1()
{
int j;
System.out.println("inside");
};
public static void main(String a1[])
{
System.out.println("in interfia");
}
}
}
------------------------------------------------------------------------------------

Can we define private and protected modifiers for variables in interfaces?
No
-----------------------------------------------------------------------------------

What is Externalizable?
Externalizable is an Interface that extends Serializable Interface. And sends data into Streams in Compressed Format. It has two methods, writeExternal(ObjectOuput out) and readExternal(ObjectInput in)
-------------------------------------------------------------------------------------

What modifiers are allowed for methods in an Interface?
Only public and abstract modifiers are allowed for methods in interfaces.
--------------------------------------------------------------------------------------

What is a local, member and a class variable?
Variables declared within a method are “local” variables. Variables declared within the class i.e not within any methods are “member” variables (global variables). Variables declared within the class i.e not within any methods and are defined as “static” are class variables
----------------------------------------------------------------------------------------

posted by Dipali at 8:29 PM | 0 comments links to this post
Thursday, September 08, 2005

General Java Interview Questions
Core Java :
What is a virtual function in C++?
Simply put, the virtual keyword enables a function to be 'virtual' which then gives possibility for that function to be overridden (redefined) in one or more descendant classes. It is a good feature since the specific function to call is determined at run-time. In other words, a virtual function allows derived classes to replace the implementation provided by the base class.

--------------------------------------------------------------------------------

What is the difference between private, protected, and public?
These keywords are for allowing privilages to components such as functions and variables.
Public: accessible to all classes
Private: accessible only to the class to which they belong
Protected: accessible to the class to which they belong and any subclasses.

--------------------------------------------------------------------------------
What is a cartesian product in PL/SQL?
When a Join condition is not specified by the programmer or is invalid(fails), PL/SQL forms a Cartesian product.
In a Cartesian product, all combinations of rows will be displayed.
For example, All rows in the first table are joined to all rows in the second table. It joins a bunch of rows and it's result is rarely useful unless you have a need to combine all rows from all tables.
-------------------------------------------------------------------------------
What is mutual exclusion? How can you take care of mutual exclusion using Java threads?
Mutual exclusion is where no two processes can access critical regions of memory at the same time.
Java provides many utilities to deal with mutual exclusion with the use of threaded programming.
For mutual exclusion, you can simply use the synchronized keyword and explicitly or implicitly provide an Object, any Object, to synchronize on.
The runtime system/Java compiler takes care of the gruesome details for you. The synchronized keyword can be applied to a class, to a method, or to a block of code. There are several methods in Java used for communicating mutually exclusive threads such as wait( ), notify( ), or notifyAll( ). For example, the notifyAll( ) method wakes up all threads that are in the wait list of an object.
--------------------------------------------------------------------------------
What are some advantages and disadvantages of Java Sockets?
Some advantages of Java Sockets:

Sockets are flexible and sufficient. Efficient socket based programming can be easily implemented for general communications.


Sockets cause low network traffic. Unlike HTML forms and CGI scripts that generate and transfer whole web pages for each new request, Java applets can send only necessary updated information.

Some disadvantages of Java Sockets:

Security restrictions are sometimes overbearing because a Java applet running in a Web browser is only able to establish connections to the machine where it came from, and to nowhere else on the network

Despite all of the useful and helpful Java features, Socket based communications allows only to send packets of raw data between applications. Both the client-side and server-side have to provide mechanisms to make the data useful in any way.

Since the data formats and protocols remain application specific, the re-use of socket based implementations is limited.

What is the difference between an Interface and an Abstract class?
An Abstract class declares have at least one instance method that is declared abstract which will be implemented by the subclasses. An abstract class can have instance methods that implement a default behavior. An Interface can only declare constants and instance methods, but cannot implement default behavior.
--------------------------------------------------------------------------------
What is the purpose of garbage collection in Java, and when is it used?
The purpose of garbage collection is to identify and discard objects that are no longer needed by a program so that their resources can be reclaimed and reused. A Java object is subject to garbage collection when it becomes unreachable to the program in which it is used.
--------------------------------------------------------------------------------
Describe synchronization in respect to multithreading.?
With respect to multithreading, synchronization is the capability to control the access of multiple threads to shared resources. Without synchonization, it is possible for one thread to modify a shared variable while another thread is in the process of using or updating same shared variable. This usually leads to significant errors.
--------------------------------------------------------------------------------
Explain different way of using thread?
The thread could be implemented by using runnable interface or by inheriting from the Thread class. The former is more advantageous, 'cause when you are going for multiple inheritance..the only interface can help.
--------------------------------------------------------------------------------
What are pass by reference and passby value?
Pass By Reference means the passing the address itself rather than passing the value. Passby Value means passing a copy of the value to be passed.
--------------------------------------------------------------------------------
What is HashMap and Map?
Map is Interface and Hashmap is class that implements that.
--------------------------------------------------------------------------------
Difference between HashMap and HashTable?
The HashMap class is roughly equivalent to Hashtable, except that it is unsynchronized and permits nulls. (HashMap allows null values as key and value whereas Hashtable doesnt allow). HashMap does not guarantee that the order of the map will remain constant over time. HashMap is non synchronized and Hashtable is synchronized.
--------------------------------------------------------------------------------
Difference between Vector and ArrayList?
Vector is synchronized whereas arraylist is not.
--------------------------------------------------------------------------------
Difference between Swing and Awt?
AWT are heavy-weight componenets. Swings are light-weight components. Hence swing works faster than AWT.
--------------------------------------------------------------------------------
What is the difference between a constructor and a method?
A constructor is a member function of a class that is used to create objects of that class. It has the same name as the class itself, has no return type, and is invoked using the new operator. A method is an ordinary member function of a class. It has its own name, a return type (which may be void), and is invoked using the dot operator.
--------------------------------------------------------------------------------
What is an Iterators?
Some of the collection classes provide traversal of their contents via a java.util.Iterator interface. This interface allows you to walk a collection of objects, operating on each object in turn. Remember when using Iterators that they contain a snapshot of the collection at the time the Iterator was obtained; generally it is not advisable to modify the collection itself while traversing an Iterator.
--------------------------------------------------------------------------------
State the significance of public, private, protected, default modifiers both singly and in combination and state the effect of package relationships on declared items qualified by these modifiers.?
public : Public class is visible in other packages, field is visible everywhere (class must be public too) private : Private variables or methods may be used only by an instance of the same class that declares the variable or method, A private feature may only be accessed by the class that owns the feature. protected : Is available to all classes in the same package and also available to all subclasses of the class that owns the protected feature.This access is provided even to subclasses that reside in a different package from the class that owns the protected feature. default :What you get by default ie, without any access modifier (ie, public private or protected).It means that it is visible to all within a particular package.
--------------------------------------------------------------------------------
What is an abstract class?
Abstract class must be extended/subclassed (to be useful). It serves as a template. A class that is abstract may not be instantiated (ie, you may not call its constructor), abstract class may contain static data. Any class with an abstract method is automatically abstract itself, and must be declared as such. A class may be declared abstract even if it has no abstract methods. This prevents it from being instantiated.
--------------------------------------------------------------------------------
What is static in java?
Static means one per class, not one for each object no matter how many instance of a class might exist. This means that you can use them without creating an instance of a class.Static methods are implicitly final, because overriding is done based on the type of the object, and static methods are attached to a class, not an object. A static method in a superclass can be shadowed by another static method in a subclass, as long as the original method was not declared final. However, you can't override a static method with a nonstatic method. In other words, you can't change a static method into an instance method in a subclass.

---------------------------------------------------------------------------------
What is final?
A final class can't be extended ie., final class may not be subclassed. A final method can't be overridden when its class is inherited. You can't change value of a final variable (is a constant).
--------------------------------------------------------------------------------
Are the imports checked for validity at compile time? e.g. will the code containing an import such as java.lang.ABCD compile?
Yes the imports are checked for the semantic validity at compile time. The code containing above line of import will not compile. It will throw an error saying,can not resolve symbol symbol : class ABCD location: package io import java.io.ABCD;
--------------------------------------------------------------------------------
Does importing a package imports the subpackages as well?
e.g. Does importing com.MyTest.* also import com.MyTest.UnitTests.*?
No you will have to import the subpackages explicitly. Importing com.MyTest.* will import classes in the package MyTest only. It will not import any class in any of it's subpackage.
--------------------------------------------------------------------------------
What is the difference between declaring a variable and defining a variable?
In declaration we just mention the type of the variable and it's name. We do not initialize it. But defining means declaration + initialization. e.g String s; is just a declaration while String s = new String ("abcd"); Or String s = "abcd"; are both definitions.
--------------------------------------------------------------------------------
What is the default value of an object reference declared as an instance variable?
null unless we define it explicitly.
--------------------------------------------------------------------------------
Can a level class be private or protected?
No. A level class can not be private or protected. It can have either "public" or no modifier. If it does not have a modifier it is supposed to have a default access.If a level class is declared as private the compiler will complain that the "modifier private is not allowed here". This means that a level class can not be private. Same is the case with protected.
--------------------------------------------------------------------------------
What type of parameter passing does Java support?
In Java the arguments are always passed by value .
--------------------------------------------------------------------------------
Primitive data types are passed by reference or pass by value?
Primitive data types are passed by value.
--------------------------------------------------------------------------------
Objects are passed by value or by reference?
Java only supports pass by value. With objects, the object reference itself is passed by value and so both the original reference and parameter copy both refer to the same object .
--------------------------------------------------------------------------------
What is serialization?
Serialization is a mechanism by which you can save the state of an object by converting it to a byte stream.
--------------------------------------------------------------------------------
How do I serialize an object to a file?
The class whose instances are to be serialized should implement an interface Serializable. Then you pass the instance to the ObjectOutputStream which is connected to a fileoutputstream. This will save the object to a file.
--------------------------------------------------------------------------------
Which methods of Serializable interface should I implement?
The serializable interface is an empty interface, it does not contain any methods. So we do not implement any methods.
--------------------------------------------------------------------------------
How can I customize the seralization process?
i.e. how can one have a control over the serialization process?
Yes it is possible to have control over serialization process. The class should implement Externalizable interface. This interface contains two methods namely readExternal and writeExternal. You should implement these methods and write the logic for customizing the serialization process.
--------------------------------------------------------------------------------
What is an abstract class?
Abstract class must be extended/subclassed (to be useful). It serves as a template. A class that is abstract may not be instantiated (ie, you may not call its constructor), abstract class may contain static data. Any class with an abstract method is automatically abstract itself, and must be declared as such. A class may be declared abstract even if it has no abstract methods. This prevents it from being instantiated.
---------------------------------------------------------------------------------
What is the common usage of serialization?
Whenever an object is to be sent over the network, objects need to be serialized. Moreover if the state of an object is to be saved, objects need to be serilazed.
-------------------------------------------------------------------------------
What is Externalizable interface?
Externalizable is an interface which contains two methods readExternal and writeExternal. These methods give you a control over the serialization mechanism. Thus if your class implements this interface, you can customize the serialization process by implementing these methods.
--------------------------------------------------------------------------------
What happens to the object references included in the object?
The serialization mechanism generates an object graph for serialization. Thus it determines whether the included object references are serializable or not. This is a recursive process. Thus when an object is serialized, all the included objects are also serialized alongwith the original obect.
--------------------------------------------------------------------------------
What one should take care of while serializing the object?
One should make sure that all the included objects are also serializable. If any of the objects is not serializable then it throws a NotSerializableException.
--------------------------------------------------------------------------------
What if the main method is declared as private?
The program compiles properly but at runtime it will give "Main method not public." message.
--------------------------------------------------------------------------------
What if the static modifier is removed from the signature of the main method?
Program compiles. But at runtime throws an error "NoSuchMethodError".
--------------------------------------------------------------------------------
What if I write static public void instead of public static void?
Program compiles and runs properly.
--------------------------------------------------------------------------------
What if I do not provide the String array as the argument to the method?
Program compiles but throws a runtime error "NoSuchMethodError".
--------------------------------------------------------------------------------
What is the first argument of the String array in main method?
The String array is empty. It does not have any element. This is unlike C/C++ where the first element by default is the program name.
--------------------------------------------------------------------------------
If I do not provide any arguments on the command line, then the String array of Main method will be empty of null?
It is empty. But not null.
--------------------------------------------------------------------------------
How can one prove that the array is not null but empty?
Print args.length. It will print 0. That means it is empty. But if it would have been null then it would have thrown a NullPointerException on attempting to print args.length.
--------------------------------------------------------------------------------
What environment variables do I need to set on my machine in order to be able to run Java programs?
CLASSPATH and PATH are the two variables.
--------------------------------------------------------------------------------
Can an application have multiple classes having main method?
Yes it is possible. While starting the application we mention the class name to be run. The JVM will look for the Main method only in the class whose name you have mentioned. Hence there is not conflict amongst the multiple classes having main method.
--------------------------------------------------------------------------------
Can I have multiple main methods in the same class?
No the program fails to compile. The compiler says that the main method is already defined in the class.
--------------------------------------------------------------------------------
Do I need to import java.lang package any time? Why ?
No. It is by default loaded internally by the JVM.
--------------------------------------------------------------------------------
Can I import same package/class twice?
Will the JVM load the package twice at runtime?
One can import the same package or same class multiple times. Neither compiler nor JVM complains abt it. And the JVM will internally load the class only once no matter how many times you import the same class.
--------------------------------------------------------------------------------
What are Checked and UnChecked Exception?
A checked exception is some subclass of Exception (or Exception itself), excluding class RuntimeException and its subclasses. Making an exception checked forces client programmers to deal with the possibility that the exception will be thrown. eg, IOException thrown by java.io.FileInputStream's read() method
----------------------------------------------------------------------------------
checked exceptions are RuntimeException and any of its subclasses. Class Error and its subclasses also are unchecked. With an unchecked exception, however, the compiler doesn't force client programmers either to catch the exception or declare it in a throws clause. In fact, client programmers may not even know that the exception could be thrown. eg, StringIndexOutOfBoundsException thrown by String's charAt() method Checked exceptions must be caught at compile time. Runtime exceptions do not need to be. Errors often cannot be.
--------------------------------------------------------------------------------
What is Overriding?
When a class defines a method using the same name, return type, and arguments as a method in its superclass, the method in the class overrides the method in the superclass. When the method is invoked for an object of the class, it is the new definition of the method that is called, and not the method definition from superclass. Methods may be overridden to be more public, not more private.
-------------------------------------------------------------------------------
What are different types of inner classes?
They are
Nested -level classes, Member classes, Local classes, Anonymous classes

Nested -level classes- If you declare a class within a class and specify the static modifier, the compiler treats the class just like any other -level class. Any class outside the declaring class accesses the nested class with the declaring class name acting similarly to a package. eg, outer.inner. -level inner classes implicitly have access only to static variables.There can also be inner interfaces. All of these are of the nested -level variety.

Member classes - Member inner classes are just like other member methods and member variables and access to the member class is restricted, just like methods and variables. This means a public member class acts similarly to a nested -level class. The primary difference between member classes and nested -level classes is that member classes have access to the specific instance of the enclosing class.

Local classes - Local classes are like local variables, specific to a block of code. Their visibility is only within the block of their declaration. In order for the class to be useful beyond the declaration block, it would need to implement a more publicly available interface.Because local classes are not members, the modifiers public, protected, private, and static are not usable.

Anonymous classes - Anonymous inner classes extend local inner classes one level further. As anonymous classes have no name, you cannot provide a constructor.

-----------------------------------------------------------------------------------
Are the imports checked for validity at compile time? e.g. will the code containing an import such as java.lang.ABCD compile?
Yes the imports are checked for the semantic validity at compile time. The code containing above line of import will not compile. It will throw an error saying,can not resolve symbol symbol : class ABCD location: package io import java.io.ABCD;
--------------------------------------------------------------------------------
Does importing a package imports the subpackages as well? e.g. Does importing com.MyTest.* also import com.MyTest.UnitTests.*?
No you will have to import the subpackages explicitly. Importing com.MyTest.* will import classes in the package MyTest only. It will not import any class in any of it's subpackage.
-------------------------------------------------------------------------------
What is the difference between declaring a variable and defining a variable?
In declaration we just mention the type of the variable and it's name. We do not initialize it. But defining means declaration + initialization. e.g String s; is just a declaration while String s = new String ("abcd"); Or String s = "abcd"; are both definitions.
--------------------------------------------------------------------------------
What is the default value of an object reference declared as an instance variable?
null unless we define it explicitly.
--------------------------------------------------------------------------------
Can a level class be private or protected?
No. A level class can not be private or protected. It can have either "public" or no modifier. If it does not have a modifier it is supposed to have a default access.If a level class is declared as private the compiler will complain that the "modifier private is not allowed here". This means that a level class can not be private. Same is the case with protected.
--------------------------------------------------------------------------------
What type of parameter passing does Java support?
In Java the arguments are always passed by value .
--------------------------------------------------------------------------------
Primitive data types are passed by reference or pass by value?
Primitive data types are passed by value.
--------------------------------------------------------------------------------
Objects are passed by value or by reference?
Java only supports pass by value. With objects, the object reference itself is passed by value and so both the original reference and parameter copy both refer to the same object .
--------------------------------------------------------------------------------
What is serialization?
Serialization is a mechanism by which you can save the state of an object by converting it to a byte stream.
--------------------------------------------------------------------------------
How do I serialize an object to a file?
The class whose instances are to be serialized should implement an interface Serializable. Then you pass the instance to the ObjectOutputStream which is connected to a fileoutputstream. This will save the object to a file.
--------------------------------------------------------------------------------
Which methods of Serializable interface should I implement?
The serializable interface is an empty interface, it does not contain any methods. So we do not implement any methods.
--------------------------------------------------------------------------------
How can I customize the seralization process?
i.e. how can one have a control over the serialization process?
Yes it is possible to have control over serialization process. The class should implement Externalizable interface. This interface contains two methods namely readExternal and writeExternal. You should implement these methods and write the logic for customizing the serialization process.
--------------------------------------------------------------------------------
What is the common usage of serialization?
Whenever an object is to be sent over the network, objects need to be serialized. Moreover if the state of an object is to be saved, objects need to be serilazed.
--------------------------------------------------------------------------------
What is Externalizable interface?
Externalizable is an interface which contains two methods readExternal and writeExternal. These methods give you a control over the serialization mechanism. Thus if your class implements this interface, you can customize the serialization process by implementing these methods.
--------------------------------------------------------------------------------
What happens to the object references included in the object?
The serialization mechanism generates an object graph for serialization. Thus it determines whether the included object references are serializable or not. This is a recursive process. Thus when an object is serialized, all the included objects are also serialized alongwith the original obect.
--------------------------------------------------------------------------------
What one should take care of while serializing the object?
One should make sure that all the included objects are also serializable. If any of the objects is not serializable then it throws a NotSerializableException.
--------------------------------------------------------------------------------
What happens to the static fields of a class during serialization?
Are these fields serialized as a part of each serialized object?
Yes the static fields do get serialized. If the static field is an object then it must have implemented Serializable interface. The static fields are serialized as a part of every object. But the commonness of the static fields across all the instances is maintained even after serialization.
--------------------------------------------------------------------------------
How are Observer and Observable used?
Objects that subclass the Observable class maintain a list of observers. When an Observable object is updated it invokes the update() method of each of its observers to notify the observers that it has changed state. The Observer interface is implemented by objects that observe Observable objects. [Received from Venkateswara Manam]
--------------------------------------------------------------------------------
What is synchronization and why is it important?
With respect to multithreading, synchronization is the capability to control the access of multiple threads to shared resources. Without synchronization, it is possible for one thread to modify a shared object while another thread is in the process of using or updating that object's value. This often leads to significant errors.
--------------------------------------------------------------------------------
How does Java handle integer overflows and underflows?
It uses those low order bytes of the result that can fit into the size of the type allowed by the operation.
--------------------------------------------------------------------------------
Does garbage collection guarantee that a program will not run out of memory?
Garbage collection does not guarantee that a program will not run out of memory. It is possible for programs to use up memory resources faster than they are garbage collected. It is also possible for programs to create objects that are not subject to garbage collection .
--------------------------------------------------------------------------------
What is the difference between preemptive scheduling and time slicing?
Under preemptive scheduling, the highest priority task executes until it enters the waiting or dead states or a higher priority task comes into existence. Under time slicing, a task executes for a predefined slice of time and then reenters the pool of ready tasks. The scheduler then determines which task should execute next, based on priority and other factors.
--------------------------------------------------------------------------------
When a thread is created and started, what is its initial state?
A thread is in the ready state after it has been created and started.
--------------------------------------------------------------------------------
What is the purpose of finalization?
The purpose of finalization is to give an unreachable object the opportunity to perform any cleanup processing before the object is garbage collected.
--------------------------------------------------------------------------------
What is the Locale class?
The Locale class is used to tailor program output to the conventions of a particular geographic, political, or cultural region.
--------------------------------------------------------------------------------
What is the difference between a while statement and a do statement?
A while statement checks at the beginning of a loop to see whether the next loop iteration should occur. A do statement checks at the end of a loop to see whether the next iteration of a loop should occur. The do statement will always execute the body of a loop at least once.
--------------------------------------------------------------------------------
What is the difference between static and non-static variables?
A static variable is associated with the class as a whole rather than with specific instances of a class. Non-static variables take on unique values with each object instance.
--------------------------------------------------------------------------------
How are this() and super() used with constructors?
this() is used to invoke a constructor of the same class. super() is used to invoke a superclass constructor.
-------------------------------------------------------------------------------
Servlets:


Explain the life cycle methods of a Servlet.
The javax.servlet.Servlet interface defines the three methods known as life-cycle method. public void init(ServletConfig config) throws ServletException public void service( ServletRequest req, ServletResponse res) throws ServletException, IOException public void destroy() First the servlet is constructed, then initialized wih the init() method. Any request from client are handled initially by the service() method before delegating to the doXxx() methods in the case of HttpServlet. The servlet is removed from service, destroyed with the destroy() methid, then garbaged collected and finalized.
--------------------------------------------------------------------------------
What is the difference between the getRequestDispatcher(String path) method of javax.servlet.ServletRequest interface and javax.servlet.ServletContext interface?
The getRequestDispatcher(String path) method of javax.servlet.ServletRequest interface accepts parameter the path to the resource to be included or forwarded to, which can be relative to the request of the calling servlet. If the path begins with a "/" it is interpreted as relative to the current context root.
The getRequestDispatcher(String path) method of javax.servlet.ServletContext interface cannot accepts relative paths. All path must sart with a "/" and are interpreted as relative to curent context root.
--------------------------------------------------------------------------------
Explain the directory structure of a web application.
The directory structure of a web application consists of two parts. A private directory called WEB-INF A public resource directory which contains public resource folder. WEB-INF folder consists of 1. web.xml
2. classes directory
3. lib directory
--------------------------------------------------------------------------------
What are the common mechanisms used for session tracking?
Cookies SSL sessions URL- rewriting
--------------------------------------------------------------------------------
Explain ServletContext.
ServletContext interface is a window for a servlet to view it's environment. A servlet can use this interface to get information such as initialization parameters for the web applicationor servlet container's version. Every web application has one and only one ServletContext and is accessible to all active resource of that application.
--------------------------------------------------------------------------------
What is preinitialization of a servlet?
A container doesnot initialize the servlets ass soon as it starts up, it initializes a servlet when it receives a request for that servlet first time. This is called lazy loading. The servlet specification defines the element, which can be specified in the deployment descriptor to make the servlet container load and initialize the servlet as soon as it starts up. The process of loading a servlet before any request comes in is called preloading or preinitializing a servlet.
--------------------------------------------------------------------------------
What is the difference between Difference between doGet() and doPost()?
A doGet() method is limited with 2k of data to be sent, and doPost() method doesn't have this limitation. A request string for doGet() looks like the following: http://www.allapplabs.com/svt1?p1=v1&p2=v2&...&pN=vN


doPost() method call doesn't need a long text tail after a servlet name in a request. All parameters are stored in a request itself, not in a request string, and it's impossible to guess the data transmitted to a servlet only looking at a request string.
--------------------------------------------------------------------------------
What is the difference between HttpServlet and GenericServlet?
A GenericServlet has a service() method aimed to handle requests.
HttpServlet extends GenericServlet and adds support for doGet(), doPost(), doHead() methods (HTTP 1.0) plus doPut(), doOptions(), doDelete(), doTrace() methods (HTTP 1.1). Both these classes are abstract.
---------------------------------------------------------------------------------
JSP:
What is a output comment?
A comment that is sent to the client in the viewable page source.The JSP engine handles an output comment as uninterpreted HTML text, returning the comment in the HTML output sent to the client. You can see the comment by viewing the page source from your Web browser. JSP Syntax Example 1 Displays in the page source:
--------------------------------------------------------------------------------
What is a Hidden Comment?
A comments that documents the JSP page but is not sent to the client. The JSP engine ignores a hidden comment, and does not process any code within hidden comment tags. A hidden comment is not sent to the client, either in the displayed JSP page or the HTML page source. The hidden comment is useful when you want to hide or "comment out" part of your JSP page. You can use any characters in the body of the comment except the closing --%> combination. If you need to use --%> in your comment, you can escape it by typing --%\>. JSP Syntax Examples
--------------------------------------------------------------------------------
What is a _Expression?
An _expression tag contains a scripting language _expression that is evaluated, converted to a String, and inserted where the _expression appears in the JSP file. Because the value of an _expression is converted to a String, you can use an _expression within text in a JSP file. Like You cannot use a semicolon to end an _expression
--------------------------------------------------------------------------------
What is a Declaration?
A declaration declares one or more variables or methods for use later in the JSP source file. A declaration must contain at least one complete declarative statement. You can declare any number of variables or methods within one declaration tag, as long as they are separated by semicolons. The declaration must be valid in the scripting language used in the JSP file.
--------------------------------------------------------------------------------
What is a Scriptlet?
A scriptlet can contain any number of language statements, variable or method declarations, or expressions that are valid in the page scripting language.Within scriptlet tags, you can

1.Declare variables or methods to use later in the file (see also Declaration).

2.Write expressions valid in the page scripting language (see also _Expression).

3.Use any of the JSP implicit objects or any object declared with a tag.

You must write plain text, HTML-encoded text, or other JSP tags outside the scriptlet. Scriptlets are executed at request time, when the JSP engine processes the client request. If the scriptlet produces output, the output is stored in the out object, from which you can display it.
--------------------------------------------------------------------------------
What are implicit objects? List them?
Certain objects that are available for the use in JSP documents without being declared first. These objects are parsed by the JSP engine and inserted into the generated servlet. The implicit objects re listed below request response pageContext session application out config page exception
--------------------------------------------------------------------------------
Difference between forward and sendRedirect?
When you invoke a forward request, the request is sent to another resource on the server, without the client being informed that a different resource is going to process the request. This process occurs completly with in the web container. When a sendRedirtect method is invoked, it causes the web container to return to the browser indicating that a new URL should be requested. Because the browser issues a completly new request any object that are stored as request attributes before the redirect occurs will be lost. This extra round trip a redirect is slower than forward.
--------------------------------------------------------------------------------
What are the different scope valiues for the ?
The different scope values for are
1. page
2. request
3.session
4.application
--------------------------------------------------------------------------------
Explain the life-cycle mehtods in JSP?
THe generated servlet class for a JSP page implements the HttpJspPage interface of the javax.servlet.jsp package. Hte HttpJspPage interface extends the JspPage interface which inturn extends the Servlet interface of the javax.servlet package. the generated servlet class thus implements all the methods of the these three interfaces.

The JspPage interface declares only two mehtods - jspInit() and jspDestroy() that must be implemented by all JSP pages regardless of the client-server protocol.

However the JSP specification has provided the HttpJspPage interfaec specifically for the JSp pages serving HTTP requests.
This interface declares one method _jspService(). The jspInit()- The container calls the jspInit() to initialize te servlet instance.It is called before any other method, and is called only once for a servlet instance.
The _jspservice()- The container calls the _jspservice() for each request, passing it the request and the response objects.
The jspDestroy()- The container calls this when it decides take the instance out of service. It is the last method called n the servlet instance.

posted by Arpan The Progress at 12:17 AM 0 comments
C++

C++ Interview Questions

Is it possible to have Virtual Constructor? If yes, how?If not, Why not possible ?
There is nothing like Virtual Constructor.
The Constructor cant be virtual as the constructor is a code which is responsible for creating a instance of a class and it cant be delegated to any other object by virtual keyword means.
--------------------------------------------------------------------------------
What about Virtual Destructor?
Yes there is a Virtual Destructor. A destructor can be virtual as it is possible as at runtime depending on the type of object baller is balling to , proper destructor will be called.
--------------------------------------------------------------------------------
What is Pure Virtual Function? Why and when it is used ?
The abstract class whose pure virtual method has to be implemented by all the classes which derive on these. Otherwise it would result in a compilation error.
This construct should be used when one wants to ensure that all the derived classes implement the method defined as pure virtual in base class.
--------------------------------------------------------------------------------
What is problem with Runtime type identification?
The run time type identification comes at a cost of performance penalty. Compiler maintains the class.
--------------------------------------------------------------------------------
How Virtual functions call up is maintained?
Through Look up tables added by the compile to every class image. This also leads to performance penalty.
--------------------------------------------------------------------------------
Can inline functions have a recursion?
No.
Syntax wise It is allowed. But then the function is no longer Inline. As the compiler will never know how deep the recursion is at compilation time.
--------------------------------------------------------------------------------
How do you link a C++ program to C functions?
By using the extern "C" linkage specification around the C function declarations.
Programmers should know about mangled function names and type-safe linkages. Then they should explain how the extern "C" linkage specification statement turns that feature off during compilation so that the linker properly links function calls to C functions.
--------------------------------------------------------------------------------
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.
--------------------------------------------------------------------------------
How many ways are there to initialize an int with a constant?
1. int foo = 123;
2. int bar(123);
-------------------------------------------------------------------------------
What is your reaction to this line of code? delete this;
It is not a good programming Practice.
A good programmer will insist that you should absolutely never use the statement if the class is to be used by other programmers and instantiated as static, extern, or automatic objects. That much should be obvious.
The code has two built-in pitfalls. First, if it executes in a member function for an extern, static, or automatic object, the program will probably crash as soon as the delete statement executes. There is no portable way for an object to tell that it was instantiated on the heap, so the class cannot assert that its object is properly instantiated. Second, when an object commits suicide this way, the using program might not know about its demise. As far as the instantiating program is concerned, the object remains in scope and continues to exist even though the object did itself in. Subsequent dereferencing of the baller can and usually does lead to disaster. I think that the language rules should disallow the idiom, but that's another matter.
--------------------------------------------------------------------------------
What is the difference between a copy constructor and an overloaded assignment operator?
A copy constructor constructs a new object by using the content of the argument object. An overloaded assignment operator assigns the contents of an existing object to another existing object of the same class.
--------------------------------------------------------------------------------
When should you use multiple inheritance?
There are three acceptable answers:- "Never," "Rarely," and "When the problem domain cannot be accurately modeled any other way."
Consider an Asset class, Building class, Vehicle class, and CompanyCar class. All company cars are vehicles. Some company cars are assets because the organizations own them. Others might be leased. Not all assets are vehicles. Money accounts are assets. Real estate holdings are assets. Some real estate holdings are buildings. Not all buildings are assets. Ad infinitum. When you diagram these relationships, it becomes apparent that multiple inheritance is a likely and intuitive way to model this common problem domain. The applicant should understand, however, that multiple inheritance, like a chainsaw, is a useful tool that has its perils, needs respect, and is best avoided except when nothing else will do.
--------------------------------------------------------------------------------
What is a virtual destructor?
The simple answer is that a virtual destructor is one that is declared with the virtual attribute.
The behavior of a virtual destructor is what is important. If you destroy an object through a baller or reference to a base class, and the base-class destructor is not virtual, the derived-class destructors are not executed, and the destruction might not be comple
--------------------------------------------------------------------------------
Can a constructor throw a exception? How to handle the error when the constructor fails?
The constructor never throws a error.
--------------------------------------------------------------------------------
What are the debugging methods you use when came across a problem?
Debugging with tools like :
GDB, DBG, Forte, Visual Studio.

Analyzing the Core dump.

Using tusc to trace the last system call before crash.

Putting Debug statements in the program source code.
--------------------------------------------------------------------------------
How the compilers arranges the various sections in the executable image?
The executable had following sections:-
Data Section (uninitialized data variable section, initialized data variable section )
Code Section
Remember that all static variables are allocated in the initialized variable section.
--------------------------------------------------------------------------------
Explain the ISA and HASA class relationships. How would you implement each in a class design?
A specialized class "is" a specialization of another class and, therefore, has the ISA relationship with the other class.
This relationship is best implemented by embedding an object of the Salary class in the Employee class.
-------------------------------------------------------------------------------
When is a template a better solution than a base class?
When you are designing a generic class to contain or otherwise manage objects of other types, when the format and behavior of those other types are unimportant to their containment or management, and particularly when those other types are unknown (thus, the generality) to the designer of the container or manager class.
--------------------------------------------------------------------------------
What are the differences between a C++ struct and C++ class?
The default member and base-class access specifies are different.
This is one of the commonly misunderstood aspects of C++. Believe it or not, many programmers think that a C++ struct is just like a C struct, while a C++ class has inheritance, access specifies, member functions, overloaded operators, and so on. Actually, the C++ struct has all the features of the class. The only differences are that a struct defaults to public member access and public base-class inheritance, and a class defaults to the private access specified and private base-class inheritance.
--------------------------------------------------------------------------------
How do you know that your class needs a virtual destructor?
If your class has at least one virtual function, you should make a destructor for this class virtual. This will allow you to delete a dynamic object through a baller to a base class object. If the destructor is non-virtual, then wrong destructor will be invoked during deletion of the dynamic object.
--------------------------------------------------------------------------------
What is the difference between new/delete and malloc/free?
Malloc/free do not know about constructors and destructors. New and delete create and destroy objects, while malloc and free allocate and deallocate memory.
--------------------------------------------------------------------------------
What happens when a function throws an exception that was not specified by an exception specification for this function?
Unexpected() is called, which, by default, will eventually trigger abort().
--------------------------------------------------------------------------------
Can you think of a situation where your program would crash without reaching the breakball, which you set at the beginning of main()?
C++ allows for dynamic initialization of global variables before main() is invoked. It is possible that initialization of global will invoke some function. If this function crashes the crash will occur before main() is entered.
--------------------------------------------------------------------------------
What issue do auto_ptr objects address?
If you use auto_ptr objects you would not have to be concerned with heap objects not being deleted even if the exception is thrown.
--------------------------------------------------------------------------------
Is there any problem with the following:
char *a=NULL; char& p = *a;?
The result is undefined. You should never do this. A reference must always refer to some object.
--------------------------------------------------------------------------------
Why do C++ compilers need name mangling?
Name mangling is the rule according to which C++ changes function's name into function signature before passing that function to a linker. This is how the linker differentiates between different functions with the same name.
--------------------------------------------------------------------------------
What is Polymorphism?
'Polymorphism' is an object oriented term. Polymorphism may be defined as the ability of related objects to respond to the same message with different, but appropriate actions. In other words, polymorphism means taking more than one form. Polymorphism leads to two important aspects in Object Oriented terminology - Function Overloading and Function Overriding. Overloading is the practice of supplying more than one definition for a given function name in the same scope. The compiler is left to pick the appropriate version of the function or operator based on the arguments with which it is called. Overriding refers to the modifications made in the sub class to the inherited methods from the base class to change their behaviour.
--------------------------------------------------------------------------------
What is Operator overloading?
When an operator is overloaded, it takes on an additional meaning relative to a certain class. But it can still retain all of its old meanings.
Examples:
1) The operators >> and << may be used for I/O operations because in the header, they are overloaded.
2) In a stack class it is possible to overload the + operattor so that it appends the contents of one stack to the contents of another. But the + operator still retains its original meaning relative to other types of data.
--------------------------------------------------------------------------------
What is the difference between run time binding and compile time binding?
Dynamic Binding :
The address of the functions are determined at runtime rather than @ compile time. This is also known as "Late Binding".

Static Binding :
The address of the functions are determined at compile time rather than @ run time. This is also known as "Early Binding"
--------------------------------------------------------------------------------
When constructing an XML DTD, how do you create an external entity reference in an attribute value?

Every interview session should have at least one trick question. Although possible when using SGML, XML DTDs don't support defining external entity references in attribute values. It's more important for the candidate to respond to this question in a logical way than than the candidate know the somewhat obscure answer.
--------------------------------------------------------------------------------
How would you build a search engine for large volumes of XML data?
The way candidates answer this question may provide insight into their view of XML data. For those who view XML primarily as a way to denote structure for text files, a common answer is to build a full-text search and handle the data similarly to the way Internet portals handle HTML pages. Others consider XML as a standard way of transferring structured data between disparate systems. These candidates often describe some scheme of importing XML into a relational or object database and relying on the database's engine for searching. Lastly, candidates that have worked with vendors specializing in this area often say that the best way the handle this situation is to use a third party software package optimized for XML data.