Advanced Java Interview Questions -14

Advanced Java Interview Questions -14

1 Does Java support multiple inheritance ?

This is the trickiest question in Java, if C++ can support direct multiple inheritance than why not Java is the argument Interviewer often give. See Why multiple inheritance is not supported in Java to answer this tricky Java question.

2 What will happen if we put a key object in a HashMap which is already there ?

This tricky Java questions is part of How HashMap works in Java, which is also a popular topic to create confusing and tricky question in Java. well if you put the same key again than it will replace the old mapping because HashMap doesn’t allow duplicate keys. See How HashMap works in Java for more tricky Java questions from HashMap.

3 If a method throws NullPointerException in super class, can we override it with a method which throws RuntimeException?

One more tricky Java questions from overloading and overriding concept. Answer is you can very well throw super class of RuntimeException in overridden method but you can not do same if its checked Exception. See Rules of method overriding in Java for more details.

4 What is the issue with following implementation of compareTo() method in Java?

public int compareTo(Object o){
Employee emp = (Employee) emp;
return –;

5 Can you override private or static method in Java ?
Another popular Java tricky question, As I said method overriding is a good topic to ask trick questions in Java.  Anyway, you can not override private or static method in Java, if you create similar method with same return type and same method arguments that’s called method hiding. See Can you override private method in Java or more details.

6 What will happen if you call return statement or System.exit on try or catch block ? will finally block execute?

This is a very popular tricky Java question and its tricky because many programmer think that finally block always executed. This question challenge that concept by putting return statement in try or catch block or calling System.exit from try or catch block. Answer of this tricky question in Java is that finally block will execute even if you put return statement in try block or catch block but finally block won’t run if you call System.exit form try or catch.

7 where id is an integer number ?
Well three is nothing wrong in this Java question until you guarantee that id is always positive. This Java question becomes tricky when you can not guaranteed id is positive or negative. If id is negative than subtraction may overflow and produce incorrect result. See How to override compareTo method in Java for complete answer of this Java tricky question for experienced programmer.

8 How do you ensure that N thread can access N resources without deadlock
If you are not well versed in writing multi-threading code then this is real tricky question for you. This Java question can be tricky even for experienced and senior programmer, who are not really exposed to deadlock and race conditions. Key point here is order, if you acquire resources in a particular order and release resources in reverse order you can prevent deadlock. See how to avoid deadlock in Java for a sample code example.

9 What is difference between CyclicBarrier and CountDownLatch in Java
Relatively newer Java tricky question, only been introduced form Java 5. Main difference between both of them is that you can reuse CyclicBarrier even if Barrier is broken but you can not reuse CountDownLatch in Java. See CyclicBarrier vs CountDownLatch in Java for more differences.

10 What is difference between StringBuffer and StringBuilder in Java ?
Classic Java questions which some people thing tricky and some consider very easy. StringBuilder in Java is introduced in Java 5 and only difference between both of them is that Stringbuffer methods are synchronized while StringBuilder is non synchronized. See StringBuilder vs StringBuffer for more differences.

11 Can you access non static variable in static context?

Another tricky Java question from Java fundamentals. No you can not access static variable in non static context in Java. Read why you can not access non-static variable from static method to learn more about this tricky Java questions.

12. Can you write critical section code for singleton?

This core Java question is followup of previous question and expecting candidate to write Java singleton using double checked locking. Remember to use volatile variable to make Singleton thread-safe. check 10 Interview questions on Singleton Pattern in Java for more details and questions answers

13. Can you write code for iterating over hashmap in Java 4 and Java 5 ?

Tricky one but he managed to write using while and for loop.

14. When do you override hashcode and equals() ?

Whenever necessary especially if you want to do equality check or want to use your object as key in HashMap. check this for writing equals method correctly 5 tips on equals in Java

15. What will be the problem if you don’t override hashcode() method ?

You will not be able to recover your object from hash Map if that is used as key in HashMap.
See here  How HashMap works in Java for detailed explanation.

16. Is it better to synchronize critical section of getInstance() method or whole getInstance() method ?
Answer is critical section because if we lock whole method than every time some one call this method will have to wait even though we are not creating any object)

17. What is the difference when String is gets created using literal or new() operator ?
When we create string with new() its created in heap and not added into string pool while String created using literal are created in String pool itself which exists in Perm area of heap.

18. Does not overriding hashcode() method has any performance implication ?
This is a good question and open to all , as per my knowledge a poor hashcode function will result in frequent collision in HashMap which eventually increase time for adding an object into Hash Map.

19. What’s wrong using HashMap in multithreaded environment? When get() method go to infinite loop ?
Another good question. His answer was during concurrent access and re-sizing.

20. Give a simplest way to find out the time a method takes for execution without using any profiling tool?
this questions is suggested by @Mohit
Read the system time just before the method is invoked and immediately after method returns. Take the time difference, which will give you the time taken by a method for execution.

To put it in code…

long start = System.currentTimeMillis ();
method ();
long end = System.currentTimeMillis ();

System.out.println (“Time taken for execution is ” + (end – start));

Remember that if the time taken for execution is too small, it might show that it is taking zero milliseconds for execution. Try it on a method which is big enough, in the sense the one which is doing considerable amout of processing

21. Which two method you need to implement for key Object in HashMap ?

In order to use any object as Key in HashMap, it must implements equals and hashcode method in Java. Read How HashMap works in Java for detailed explanation on how equals and hashcode method is used to put and get object from HashMap. You can also see my post 5 tips to correctly override equals in Java to learn more about equals.

22. Where does these  two method comes in picture during get operation?

This core Java interview question is follow-up of previous Java question and candidate should know that once you mention hashCode, people are most likely ask How its used in HashMap. See How HashMap works in Java for detailed explanation.

23. How do you handle error condition while writing stored procedure or accessing stored procedure from java?

This is one of the tough Java interview question and its open for all, my friend didn’t know the answer so he didn’t mind telling me. my take is that stored procedure should return error code if some operation fails but if stored procedure itself fail than catching SQLException is only choice.

24. What is difference between Executor.submit() and Executer.execute() method ?

This Java interview question is from my list of Top 15 Java multi-threading question answers, Its getting popular day by day because of huge demand of Java developer with good concurrency skill. Answer of this Java interview question is that former returns an object of Future which can be used to find result from worker thread)

By the way @vinit Saini suggested a very good point related to this core Java interview question

There is a difference when looking at exception handling. If your tasks throws an exception and if it was submitted with execute this exception will go to the uncaught exception handler (when you don’t have provided one explicitly, the default one will just print the stack trace to System.err). If you submitted the task with submit any thrown exception, checked exception or not, is then part of the task’s return status. For a task that was submitted with submit and that terminates with an exception, the Future.get will re-throw this exception, wrapped in an ExecutionException.

25. What is the difference between factory and abstract factory pattern?

This Java interview question is from my list of 20 Java design pattern interview question and its open for all of you to answer.
@Raj suggested
Abstract Factory provides one more level of abstraction. Consider different factories each extended from an Abstract Factory and responsible for creation of different hierarchies of objects based on the type of factory. E.g. AbstractFactory extended by AutomobileFactory, UserFactory, RoleFactory etc. Each individual factory would be responsible for creation of objects in that genre.
You can also refer What is Factory method design pattern in Java to know more details.

26. What is Singleton? is it better to make whole method synchronized or only critical section synchronized ?

Singleton in Java is a class with just one instance in whole Java application, for example java.lang.Runtime is a Singleton class. Creating Singleton was tricky prior Java 4 but once Java 5 introduced Enum its very easy. see my article How to create thread-safe Singleton in Java for more details on writing Singleton using enum and double checked locking which is purpose of this Java interview question.

27. What is immutable object? Can you write immutable object?

Immutable classes are Java classes whose objects can not be modified once created. Any modification in Immutable object result in new object. For example is String is immutable in Java. Mostly Immutable are also final in Java, in order to prevent sub class from overriding methods in Java which can compromise Immutability. You can achieve same functionality by making member as non final but private and not modifying them except in constructor.

28. Does all property of immutable object needs to be final?

Not necessary as stated above you can achieve same functionality by making member as non final but private and not modifying them except in constructor.

29. What is the difference between creating String as new() and literal?

When we create string with new() Operator, it’s created in heap and not added into string pool while String created using literal are created in String pool itself which exists in PermGen area of heap.

String s = new String(“Test”);

does not  put the object in String pool , we need to call String.intern() method which is used to put  them into String pool explicitly. its only when you create String object as String literal e.g. String s = “Test” Java automatically put that into String pool.

30. How does substring () inside String works?

Another good Java interview question, I think answer is not sufficient but here it is “Substring creates new object out of source string by taking a portion of original string”. see my post How SubString works in Java for detailed answer of this Java question.

31 Can we compare String using == operator? What is risk?
As discussed in previous String question, You can compare String using equality operator but that is not suggested or advised because equality operator is used to compare primitives and equals() method should be used to compare objects. As we have seen in pitfall of autoboxing in Java that how equality operator can cause subtle issue while comparing primitive to Object, any way String is free from that issue because it doesn’t have corresponding primitive type and not participate in autoboxing. Almost all the time comparing String means comparing contents of String i.e. characters and equals() method is used to perform character based comparison. equals() return true if two String points to same object or two String has same contents while == operator returns true if two String object points to same object but return false if two different String object contains same contents. That explains why sometime it works and sometime it doesn’t. In short always use equals method in Java to check equality of two String object.

32 How substring method work in Java
This is one of the tricky Java question relate to String and until you are familiar with internals of String class, its difficult to answer. Substring shares same character array as original String which can create memory leak if original String is quite big and not required to retain in memory but unintentionally retained by substring which is very small in size and prevents large array from begin claimed during Garbage collection in Java. See How Substring works in Java for more details.

33 What is String pool in Java
Another tough Java question asked in  String interview. String pool is a special storage area in Java heap, mostly located on PerGen space, to store String literals like “abc”. When Java program creates a new String using String literal, JVM checks for that String in pool and if String literal is already present in pool than same object is returned instead of creating a whole new object. String pool check is only performed when you create String as literal, if you create String using new() operator, a new String object will be created even if String with same content is available in pool.

34 What does intern() method do in Java
As discussed in previous String interview question, String object crated by new() operator is by default not added in String pool as opposed to String literal. intern() method allows to put an String object into pool.

35 Does String is thread-safe in Java
If you are familiar with the concept of immutability and thread-safety you can easily answer this String interview question in Java. Since String is immutable, it is thread-safe and it can be shared between multiple thread without external synchronization.

That’s all on Java String interview question. In Summary there are lot of specifics about String which needs to be know for any one who has started Java programming and these String question will not just help to perform better on Java Interviews but also opens new door of learning about String. I didn’t know many String related concepts until I come across these question which motivated to research and learn more about String in Java.

36 What is String in Java ? Is String is data type?

String in Java is not a primitive data type like int, long or double.  String is a class or in more simple term a user defined type. This is confusing for some one who comes from C background. String is defined in java.lang package and wrappers its content in a character array. String provides equals() method to compare two String and provides various other method to operate on String like toUpperCase() to convert String into upper case, replace() to replace String contents, substring() to get substring, split() to split long String into multiple String.

37 Why String is final in Java

String is final by design in Java, some of the points which makes sense why String is final is Security, optimization and to maintain pool of String in Java. for details on each of this point see Why String is final in Java.

38 What is Difference between String and StringBuffer in Java

This is probably the most common question on String I have seen in Java interviews. Though String and Stringbuffer are two different class they are used in context of concatenating two Strings, Since String is immutable in Java every operation which changes String produces new String, which can be avoided by using Stringbuffer. See String vs StringBuffer  for more details.

39 What is difference in String on C and Java

If you have mentioned C in your resume, then you are likely to face this String interview question. Well C String and Java String are completely different to each other, C String is a null terminated character array while String in Java is an Object. Also String is more feature rich in Java than C.

40 Why char array is better than String for storing password?

This String interview question is debatable and you might not agree with interviewer but this is also a chance to show that how deep and differently you can think of. One of the reason which people give Why you should store password in char array over String is related to immutability, since its not possible to remove erase contents of String but you can erase contents of char array. See Why char array preferred over String for password for complete discussion.

41 How do you compare two String in Java ?

This is another common String interview question which appears on fresher level interviews. There are multiple ways to compare two String like equals() method, equalsIgnoreCase() etc, You can also see 4 ways to compare String in Java for more examples. Main thing which interviewer checks is that whether candidate mentioned equality operator or not “==”, comparing String with equality operator is common mistake which works in some case and doesn’t work in other. next String interview question is follow-up up of this.

42 Why there are no global variables in Java?

Global variables are globally accessible and hence can create collisions in namespace.

43 What is the Java API?

It a large collection of software components that provide capabilities, such as graphical user interface (GUI) widgets.

44 Explain StringTokenizer.

It is utility class that are used to break up string.


StringTokenizer str = new StringTokenizer(“Welcome”);

while (str.hasMoreTokens()) {



45 Difference between the boolean & operator and the && operator.

When boolean & operator is evaluated, both operands are evaluated
&& operator is a short cut operator.

When && operator is evaluated, the first operand is evaluated.
When first operand returns a value of true then the second operand is evaluated.
When first operand evaluates to false, the evaluation of the second operand is skipped.

46 Does Java support pointers?

Java doesn’t support the usage of pointers. Improper handling of pointers leads to memory leaks which is why pointer concept hasn’t found place in Java.

Swing and Awt

47 AWT are heavy-weight componenets.

Swings are light-weight components and this is reason why swing works faster than AWT.

48 Pass by reference and passby value

Pass By Reference is the passing the address itself rather than passing the value.

Passby Value is passing a copy of the value to be passed.

49 Abstract class

It must be extended or subclassed.
It acts as a template.
It may contain static data.
A class may be declared abstract even if it has no abstract methodsand this prevents it from being instantiated.

50 What is chained exceptions in java?

When in a program the first exception causes another exception that is termed as Chained Exception. Chained exceptions helps in finding the root cause of the exception that occurs during application’s execution. The constructors that support chained exceptions in Throwable classes are:

Throwable initCause(Throwable)
Throwable(String, Throwable)
Throwable getCause()

51 When is the main thread stop in java?

When we execute the java program, it call the main() method because main() method is the first thread in the program. This main() method or thread invokes the other thread which is required for the complete execution of the program. The main thread should be the last thread in the program to end. so to make main() method to be last we make sure when we called to another function by giving execution control to that must return the control back to the main() method.

52 What are the ways to create child threads?

There are two ways to create java threads:
Implementing the Runnable interface: this overcomes the limitation of inheriting from only one parent class Thread. Using Runnable interface, lays a path to ground work of a class that utilizes threads
Extending Thread class: It inherits the methods and data members, fields from the class tread. In this process only one class can be inherited from the parent class Thread.
The advantage is a class can extend Thread class and also implements the Runnable interface, if required. The Runnable interface is set for implementing a thread and the class that implements the interface performs all the work.

53 Why bytecode is important to Java?

The compiled Java source code is known as byte code. We need bytecode due to following reasons:
Is independent of the input language.
Plays an important role in the execution speed of the application.
Can run on any platform irrespective of system architecture.
Can be used for internet applications where security is important
Enable us to load classes which are required for the execution of the application.
allows the web applications to run on various platforms, on various browsers on different infrastructures.
What is an Iterator and explain traversing through a collector using Iterator?
We can access each element in the Collection by using Iterators irrespective of how they are organized in the collector. Iterator can be implemented a different way for every Collection. To use an iterator to traverse through the contents of a collection we do:
Obtain an iterator by calling the collections iterator() method to the start of the collection.
Set up a loop that makes a call to hasNext(). Have the loop iterate as long as hasNext()returns true.
Within the loop, obtain each element by calling next().
remove() method is used to remove the current element in the iteration.

54 What is Race condition?

Race Condition: it is the situation when two threads raise the request for the same resource allocation, but the manner in which resources are allocated are significant, is called race conditions.
Race condition is created in program in order to run the parallel execution of program by using multiple threads in a same period.
A race condition occurs when two threads operate on same object without proper synchronization and there operation interleaves on each other.
The risk of Race condition is higher in Java.

55 What is difference between Java and JavaScript?

The difference between java and java scripts are:

Java is an Object Oriented Programming Language and capable of running on multiple operating systems with the help of interpreter whereas Java Script is the object oriented scripting language and it is embedded in HTML and runs directly on the browser.
JVM is used to executed java program on different program whereas Java Script code is not compiled they are directly run on the browser.
Java language is used to develop the software whereas java script is used providing interactivity to the simple HTML pages.

56 What is the difference between factory and abstract factory pattern?

The differences between factory and abstract factory are following:
Factory pattern is a single method but abstract factory is an object.
The Abstract Factory pattern is one level of abstraction higher than the factory pattern.
Factory pattern generally returns the common parent class or method whereas the abstract factory pattern returns the one of the several factories.

57 What is Singleton?

Singleton in Java is a class with just one instance in whole Java application.

This make sure that only one instance of a class is created.
getInstance() method is used to get single instance of the class.
It creates a global point to access all object
What is the difference between JAR and WAR files?
The differences between JAR and WAR files are:
JAR files (Java Archive) allows combining many files into one whereas WAR files (Web Application Archive) stores XML, java classes, and JavaServer pages for Web Application purposes.
JAR is used to hold Java classes in a library whereas in WAR files are stored in lib directory of the application.
In this EJB module which contains enterprise java beans class files and EJB deployment descriptor are packed as JAR files with .jar extension whereas in WAR web modules which contains Servlet class files, JSP Files, GIF and HTML files are packaged as JAR file with .war extension.

58 Can we compare String using equality operator (==) operator?

We can compare String using equality operator. But we mostly use equals() method because of following reasons:
The equality operator is used to compare primitives values only where as equals method() should be used to compare objects.
The equality operator can invoke subtle issue while comparing primitive to Object. Where as equals() method is used to perform character based comparison.
equals() return true if two String represent to the same object or when both strings contents are exactly same but equality() perator returns true if two String object represents to same object but return false if two different String object contains same contents

59 What is intern() method in Java?

The intern() method is of String class. The intern() method is supposed to return the String from the String pool if the String is found in String pool, otherwise a new string object will be added in String pool and the reference of this String is returned.
String str1 = “hello”;
String str2 = “hello”;
String str3 = “hello”.intern();
if ( s1 == s2 ){
System.out.println(“str1 and str2 are same”);
if ( str1 == str3 ){
System.out.println(“str1 and str3 are same” );
We are assuming that str1 and str3 are same will be printed as str3 is interned, and str1 and str2 are same will not be printed. Actual output is: both lines are printed. Which make clear that by default String constants are interned?

60 When is class garbage collected?

Java uses the garbage collector to free memory which is occupied by those objects which is no more reference by any of the program. An object becomes eligible for Garbage Collection when no live thread can access it. There are many ways to make a class reachable and thus prevent it from being eligible for Garbage Collection:

Objects of that class are still reachable.
Class object representing the class is still reachable.
ClassLoader that loaded the class is still reachable.
Other classes loaded by the ClassLoader are still reachable.
When all of the above are false, then the ClassLoader together with all classes it loaded are eligible for Garbage Collection.

61 What is the difference between a Choice and a List?

The between Choice and list are following:
Choice class presents a pop-up menu of choices whereas List is a collection of different visible item.
Choice is displayed in a compact form, to see the list of available choices we need to scroll down whereas list displays the entire available items.
Choice allows selecting only one items but List supports the selection of one or more List items.
Lists typically allow duplicate elements selection. List allow pairs of elements e1 and e2 such that e1.equals(e2), and they typically allow multiple null elements if they allow null elements at all.

62 What is JCA in java?

Java Cryptography Architecture term from Sun for implementing security functions for the Java platform. It provides a platform and gives architecture and APIs for encryption and decryption. JCA is used by the developer to combine the application with the security measure. A programmer uses the JCA to meet the security measure. It helps in performing the third partly security rules. It uses the hash table, encryption message digest, etc to implement the security.
What is JPA in java?
The Java Persistence API is enabling us to create the persistence layer for desktop and web applications. Java Persistence deals in following:
Java Persistence API
Query language
Java Persistence Criteria API
Object mapping metadata

63 What is Single Threaded Model in Servlets?

Single Thread Model is a marker interface which contains no methods and variable in it.
When using Single thread model with Servlet, it make sure that that only one thread can be executed at a time. It avoids running of two or more thead simultaneously.
If we wants to make single threaded we can implement this interface in the following fashion.
public class SingleThreadedTest implements SingleThreadModel
//some code

64 What are the different Authentication Options available in Servets?

Authentication options available in Servlets: There are four different options for authentication in servlet:
1. Basic Authentication: Username and password provided by the client to authenticate the user.
2. Form-based authentication- In this the login form is made by the programmer by using HTML.
3. Digest Authentication- It is similar to basic authentication but in this the passwords are encrypted using Hash formula. This makes digest more secured.
4. Client certificate Authentication- It requires that each client accessing the resource has a certificate that it send to authenticate itself. This requires SSL protocol.

65 What is the disadvantage of garbage collector?

Garbage Collector runs in its own thread which affects the performance of the system. It increases the workload of JVM because it constantly monitor the object which is not referenced.. The two main disadvantages of garbage collector are:
TIME: to collect all those no referenced object JVM spends a considerable amount of time by scanning the entire heap.
Mark and sweep: some time it is difficult to implement mark and sweep in the application.

66 Does java support global variable?

No, java does not support global variable because of the following reasons:
Globally accessible: global variables are globally accessible.
Referential transparency:global variable breaks the referential transparency and also a global variable generate problem in the namespace.
Object oriented: As JAVA is object oriented language so where each variable is declared inside the class. To use this variable, object should be initialized.

67 Explain different layout manager in Java.

There are following types of layouts are used to organize or to arrange objects:

Border Layout: Have five areas for holding components: north, east, west, south and center.
Flow Layout: Default layout manager, lays out the components from left to right
Card Layout: Different components at different times are laid out, Controlled by a combo box.
Grid Layout: Group of components are laid out I equal size and displays them in certain rows and columns.
Grid Bag Layout: Flexible layout for placing components within a grid of cells.

68 What is difference between eager and lazy loading?

The difference between eager and loading are:
Eager loading means to load the data before the requirement whereas lazy loading mean that load the data only when required.
Eager loading fetch the data in one query whereas lazy loading fetch the data when needed by triggering the sub query.

69 What is JMS in Java?

Java Message Service (JMS) is used for creating the communication interface between two clients by using the message passing services. This helps the application to interact with other components irrespective of components location whether they rely on same system or connect to the main system through LAN or internet.
What is shallow cloning and deep cloning?
Shallow copy: in this object is copied without its contained objects. Shallow clone only copies the top level structure of the object not the lower levels. It is an exact bit copy of all the attributes.
Deep copy: In this object is copied along with the objects it refers to. Deep clone copies all the levels of the object from top to the bottom recursively.

70 What is the difference between applications and applets?

The differences between an Applet and an application are as follows:
Applets can be embedded in HTML pages and downloaded over the Internet whereas Applications have no special support in HTML for embedding or downloading.
Application starts execution with its main method whereas applet starts execution with its init method.
Application must be run on local machine whereas applet needs no explicit installation on local machine.
Application must be run explicitly within a java-compatible virtual machine whereas applet loads and runs itself automatically in a java-enabled browser.
Application can run with or without graphical user interface whereas applet must run within a graphical user interface.

71 What are Class loaders?

Class loader enables the program to load the class at run time. This is located in the java.lang package.
Using Class Loader we can also load the customize classes which is required for the application execution. The class loaders in Java are organized in a tree. When JVM is started three class loaders are used:
Bootstrap class loader: the core java libraries. It is written in native code.
Extensions class loader: loads the code in the extension directories. It is implemented by ExtClassLoader class.
System class loader: code found on the java.class.path which map to the system class path variables. It is implemented by AppClassLoader class. All user classes by default are load by the system class loader.

72 What is the Comparable interface?

The Comparable interface is used to sort collections and arrays of objects using the collections.sort() and java.utils. The objects of the class implementing the Comparable interface can be ordered. All classes implementing the Comparable interface must implement the compareTo() method that has the return type as an integer. The signature of the compareTo() method is as follows:
int i = object1.compareTo(object2)
If object1 < object2: The value of i returned will be negative.
If object1 > object2: The value of i returned will be positive.
If object1 = object2: The value of i returned will be zero.

73 Define Externalizable Interface and explain its purpose.
The Externizable interface extends the serializable interface.
When you use Serializable interface, your class is serialized automatically by default. But you can override writeObject() and readObject()two methods to control more complex object serailization process.
When you use Externalizable interface, you have a complete control over your class’s serialization process. The two methods to be implemented are : void readExternal(ObjectInput)
The object implements the readExternal method to restore its contents by calling the methods of DataInput for primitive types and readObject for objects, strings and arrays.
void writeExternal(ObjectOutput)
The object implements the writeExternal method to save its contents by calling the methods of DataOutput for its primitive values or calling the writeObject method of ObjectOutput for objects, strings, and arrays. < /LI> < /UL>

74 Explain the usage of serialization.

Objects are serialized when need to be sent over network.
They are serialized when the state of an object is to be saved.

75 Differences between constructors and methods.

A constructor is used to create objects of a class. A method is an ordinary member in a class.
Constructor does not have a return type. A method should have a return type.
Constructor name is the name of the class. A method name should not be the name of the class
Constructor is invoked at the time of creation of the class. Method needs to be invoked in another method by using the dot operator.
Constructor can not have ‘return’ statement. All methods that return non-void return type should have ‘return’ statement.

76 Define Method overriding. Explain its uses.

Method overriding is the process of writing functionality for methods with same signature and return type, both in super class and subclass The uses of method overriding:
Time to invest method signature is reduced
Different functionality in both super class and sub class by sharing same signature
The functionality can be enhanced
The behavior can be replaced in the sub class

77 Explain class loaders in Java with an example.

The class loader describes the behavior of converting a named class into the bits responsible for implementing that class.
Class loaders eradicate the JREs need to know anything about files and file systems when running Java programs.
A class loader creates a flat name space of class bodies that are referenced by a string name and are written as:
Class r = loadClass(String className, boolean resolveIt);

78 Can you explain shallow cloning and deep cloning?

Cloning of objects can be very useful if you use the prototype pattern or if you want to store an internal copy of an object inside an aggregation class for example.
Deep cloning – You clone the object and their constituent parts.
It should be used when it is inappropriate to separate the parts; the object is formed of, from it.
Shallow cloning – You clone only the object, not their parts. You add references to their parts.
It should be used when it is adequate to have the references added to the cloned object

79 This Can you explain static Initializers in Java?

A static initializer block resembles a method with no name, no arguments, and no return type. There is no need to refer to it from outside the class definition.
The code in a static initializer block is executed by the virtual machine when the class is loaded.
Because it is executed automatically when the class is loaded, parameters don’t make any sense, so a static initializer block doesn’t have an argument list.

80 Can you explain Native methods in Java?

The Java native method is used to merge the power of C or C++ programming into Java.
To enhance to high performance language, when efficient native Java compilers are not fully implemented, use of native method boosts the performance to at least the speed of C compiled code.
Java applications can call code written in C, C++, or assembler. This is sometimes done for performance and sometimes to access the underlying host operating system or GUI API using the JNI.

81 How are Observer and Observable used?

The observable class represents an observable object.
The object to be observed can be represented by sub-classing observable class.
When there is a change in an observable instance, an application calling the Observable’s notifyObservers method causes all of its observers to be notified of the change by a call to their update method

82 Static class loading vs. dynamic class loading.

The static class loading is done through the new operator.
Dynamic class loading is achieved through Run time type identification. Also called as reflection
This is done with the help of the following methods:
getClass(); getName(); getDeclaredFields();
Instance can also be created using forName() method. It loads the class into the current class memory.

83 What is the impact of private constructor?

Private Constructors can’t be access from any derived classes neither from another class.
So you have to provide a public function that calls the private constructor if the object has not been initialized, or you have to return an instance to the object, if it was initialized.

84 What is the purpose of the File class?

The File class provides access to the files and directories of a local file system.

85 Define inner class in Java

Class that is nested within a class is called as inner class. The inner class can access private members of the outer class. It is mainly used to implement data structure and some time called as a helper class.

86 Explain the purpose of Comparator Interface.

Comparators can be used to control the order of certain data structures and collection of objects too.
The interface can be found in java.util.Comparator
A Comparator must define a compare function which takes two Objects and returns a -1, 0, or 1
Sorting can be done implicitly by using data structures of by implementing sort methods explicitly.

87 Difference between Swing and Awt.

AWT are heavy-weight components. Swings are light-weight components. Thus, swing works faster than AWT.

88 What is Reflection API in Java?

The Reflection API allows Java code to examine classes and objects at run time.
The new reflection classes allow you to call another class’s methods dynamically at run time.
With the reflection classes, you can also examine an instance’s fields and change the fields’ contents.
It is also possible to instantiate new objects, invoke methods and get/set field values using reflection.
The Reflection API consists of the java.lang.Class class and the java.lang.reflect classes: Field, Method, Constructor, Array, and Modifier.

89 How does a servlet communicate with a JSP page?

The following code snippet shows how a servlet instantiates a bean and initializes it with FORM data posted by a browser. The bean is then placed into the request, and the call is then forwarded to the JSP page, Bean1.jsp, by means of a request dispatcher for downstream processing.
public void doPost (HttpServletRequest request, HttpServletResponse response) {
try {
govi.FormBean f = new govi.FormBean();
String id = request.getParameter(“id”);
//use the id to compute
//additional bean properties like info
//maybe perform a db query, etc.
// . . .
(“/jsp/Bean1.jsp”).forward(request, response);
} catch (Exception ex) {
. . .
The JSP page Bean1.jsp can then process fBean, after first extracting it from the default request scope via the useBean action.
jsp:useBean id=”fBean” scope=”request”
/ jsp:getProperty name=”fBean” property=”name”
/ jsp:getProperty name=”fBean” property=”addr”
/ jsp:getProperty name=”fBean” property=”age”
/ jsp:getProperty name=”fBean” property=”personalizationInfo” /

90 How do I have the JSP-generated servlet subclass my own custom servlet class, instead of the default?

One should be very careful when having JSP pages extend custom servlet classes as opposed to the default one generated by the JSP engine. In doing so, you may lose out on any advanced optimization that may be provided by the JSP engine. In any case, your new superclass has to fulfill the contract with the JSP engine by:
Implementing the HttpJspPage interface, if the protocol used is HTTP, or implementing JspPage otherwise Ensuring that all the methods in the Servlet interface are declared final Additionally, your servlet superclass also needs to do the following:
The service() method has to invoke the _jspService() method
The init() method has to invoke the jspInit() method
The destroy() method has to invoke jspDestroy()
If any of the above conditions are not satisfied, the JSP engine may throw a translation error.
Once the superclass has been developed, you can have your JSP extend it as follows:
<%@ page extends=”packageName.ServletName” %>

91 How can I prevent the word “null” from appearing in my HTML input text fields when I populate them with a resultset that has null values?

You could make a simple wrapper function, like
String blanknull(String s) {
return (s == null) ? “” : s;
then use it inside your JSP form, like
<input type=”text” name=”shoesize” value=”<%=blanknull(shoesize)% >” >

92 what is a JSP Page?

A JSP page is a text document that contains two types of text: static data, which can be expressed in any text-based format (such as HTML, WML, XML, etc), and JSP elements, which construct dynamic content.JSP is a technology that lets you mix static content with dynamically-generated content.

93 why do I need JSP technology if I already have servlets?

JSP pages are compiled into servlets, so theoretically you could write servlets to support your web-based applications. However, JSP technology was designed to simplify the process of creating pages by separating web presentation from web content. In many applications, the response sent to the client is a combination of template data and dynamically-generated data. In this situation, it is much easier to work with JSP pages than to do everything with servlets.

94 How are the JSP requests handled?

The following sequence of events happens on arrival of jsp request:
a. Browser requests a page with .jsp file extension in web server.
b. Web server reads the request.
c. Using jsp compiler, webserver converts the jsp into a servlet class that implement the javax.servletjsp.jsp page interface. The jsp file compiles only when the page is first requested or when the jsp file has been changed.
e. The response is sent to the client by the generated servlet.

95 what are the advantages of JSP?
The following are the advantages of using JSP:
a. JSP pages easily combine static templates, including HTML or XML fragments, with code that generates dynamic content.
b. JSP pages are compiled dynamically into servlets when requested, so page authors can easily make updates to presentation code. JSP pages can also be precompiled if desired.
c. JSP tags for invoking JavaBeans components manage these components completely, shielding the page author from the complexity of application logic.
d. Developers can offer customized JSP tag libraries that page authors access using an XML-like syntax.
e. Web authors can change and edit the fixed template portions of pages without affecting the application logic. Similarly, developers can make logic changes at the component level without editing the individual pages that use the logic.

96 How is a JSP page invoked and compiled?
Pages built using JSP technology are typically implemented using a translation phase that is performed once, the first time the page is called. The page is compiled into a Java Servlet class and remains in server memory, so subsequent calls to the page have very fast response times.

97 What are the implicit objects?
Implicit objects are objects that are created by the web container and contain information related to a particular request, page, or application. They are: request, response, pageContext, session, application, out, config, page, exception.

98 Is JSP technology extensible?
Yes. JSP technology is extensible through the development of custom actions, or tags, which are encapsulated in tag libraries.

99 How can I implement a thread-safe JSP page? What are the advantages and Disadvantages of using it?

You can make your JSPs thread-safe by having them implement the SingleThreadModel interface. This is done by adding the directive <%@ page isThreadSafe=”false” %> within your JSP page. With this, instead of a single instance of the servlet generated for your JSP page loaded in memory, you will have N instances of the servlet loaded and initialized, with the service method of each instance effectively synchronized. You can typically control the number of instances (N) that are instantiated for all servlets implementing SingleThreadModel through the admin screen for your JSP engine. More importantly, avoid using the tag for variables. If you do use this tag, then you should set isThreadSafe to true, as mentioned above. Otherwise, all requests to that page will access those variables, causing a nasty race condition. SingleThreadModel is not recommended for normal use. There are many pitfalls, including the example above of not being able to use <%! %>. You should try really hard to make them thread-safe the old fashioned way: by making them thread-safe.

100 How does JSP handle run-time exceptions?
You can use the errorPage attribute of the page directive to have uncaught run-time exceptions automatically forwarded to an error processing page.
For example: <%@ page errorPage=”error.jsp” %>
redirects the browser to the JSP page error.jsp if an uncaught exception is encountered during request processing. Within error.jsp, if you indicate that it is an error-processing page, via the directive: <%@ page isErrorPage=”true” %> Throwable object describing the exception may be accessed within the error page via the exception implicit object.
Note: You must always use a relative URL as the value for the errorPage attribute.

101 How do I prevent the output of my JSP or Servlet pages from being cached by the browser?

You will need to set the appropriate HTTP header attributes to prevent the dynamic content output by the JSP page from being cached by the browser. Just execute the following scriptlet at the beginning of your JSP pages to prevent them from being cached at the browser. You need both the statements to take care of some of the older browser versions.
response.setHeader(“Cache-Control”,”no-store”); //HTTP 1.1
response.setHeader(“Pragma”,”no-cache”); //HTTP 1.0
response.setDateHeader (“Expires”, 0); //prevents caching at the proxy server

102 How can I declare methods within my JSP page?
You can declare methods for use within your JSP page as declarations. The methods can then be invoked within any other methods you declare, or within JSP scriptlets and expressions. Do note that you do not have direct access to any of the JSP implicit objects like request, response, session and so forth from within JSP methods. However, you should be able to pass any of the implicit JSP variables as parameters to the methods you declare.
For example:
public String whereFrom(HttpServletRequest req) {
HttpSession ses = req.getSession();

return req.getRemoteHost();
out.print(“Hi there, I see that you are coming in from “);
<%= whereFrom(request) %>
Another Example
<%@page contentType=”text/html”%>
public void test(JspWriter writer) throws IOException{
<%@include file=”file1.jsp”%>
<%test(out);% >

103 How do I use comments within a JSP page?
You can use “JSP-style” comments to selectively block out code while debugging or simply to comment your scriptlets. JSP comments are not visible at the client. For example:
<%– the scriptlet is now commented out
out.println(“Hello World”);
You can also use HTML-style comments anywhere within your JSP page. These comments are visible at the client. For example:
<!– (c) 2004 –>
Of course, you can also use comments supported by your JSP scripting language within your scriptlets. For example, assuming Java is the scripting language, you can have:
//some comment
yet another comment
Response has already been commited error. What does it mean?
This error show only when you try to redirect a page after you already have written something in your page. This happens because HTTP specification force the header to be set up before the lay out of the page can be shown (to make sure of how it should be displayed, content-type=”text/html” or “text/xml” or “plain-text” or “image/jpg”, etc.) When you try to send a redirect status (Number is line_status_402), your HTTP server cannot send it right now if it hasn’t finished to set up the header. If not starter to set up the header, there are no problems, but if it ’s already begin to set up the header, then your HTTP server expects these headers to be finished setting up and it cannot be the case if the stream of the page is not over… In this last case it’s like you have a file started with <HTML Tag><Some Headers><Body>some output (like testing your variables.) Before you indicate that the file is over (and before the size of the page can be setted up in the header), you try to send a redirect status. It s simply impossible due to the specification of HTTP 1.0 and 1.1
Q-13.How do I use a scriptlet to initialize a newly instantiated bean?
A jsp:useBean action may optionally have a body. If the body is specified, its contents will be automatically invoked when the specified bean is instantiated. Typically, the body will contain scriptlets or jsp:setProperty tags to initialize the newly instantiated bean, although you are not restricted to using those alone.
The following example shows the “today” property of the Foo bean initialized to the current date when it is instantiated. Note that here, we make use of a JSP expression within the jsp:setProperty action.
<jsp:useBean id=”foo” >
<%=java.text.DateFormat.getDateInstance().format(new java.util.Date()) %>”/ >
<%– scriptlets calling bean setter methods go here –%>
</jsp:useBean >

104 Briefly explain about Java Server Pages technology?

JavaServer Pages (JSP) technology provides a simplified, fast way to create web pages that display dynamically-generated content. The JSP specification, developed through an industry-wide initiative led by Sun Microsystems, defines the interaction between the server and the JSP page, and describes the format and syntax of the page.

105 How can I set a cookie and delete a cookie from within a JSP page?
A cookie, mycookie, can be deleted using the following scriptlet:
//creating a cookie
Cookie mycookie = new Cookie(“aName”,”aValue”);
//delete a cookie
Cookie killMyCookie = new Cookie(“mycookie”, null);

106 Is there a way I can set the inactivity lease period on a per-session basis?

Typically, a default inactivity lease period for all sessions is set within your JSP engine admin screen or associated properties file. However, if your JSP engine supports the Servlet 2.1 API, you can manage the inactivity lease period on a per-session basis. This is done by invoking the HttpSession.setMaxInactiveInterval() method, right after the session has been created.
For example:
would reset the inactivity period for this session to 5 minutes. The inactivity interval is set in seconds.

107 How can I enable session tracking for JSP pages if the browser has disabled cookies?

We know that session tracking uses cookies by default to associate a session identifier with a unique user. If the browser does not support cookies, or if cookies are disabled, you can still enable session tracking using URL rewriting. URL rewriting essentially includes the session ID within the link itself as a name/value pair. However, for this to be effective, you need to append the session ID for each and every link that is part of your servlet response. Adding the session ID to a link is greatly simplified by means of of a couple of methods: response.encodeURL() associates a session ID with a given URL, and if you are using redirection, response.encodeRedirectURL() can be used by giving the redirected URL as input. Both encodeURL() and encodeRedirectedURL() first determine whether cookies are supported by the browser; if so, the input URL is returned unchanged since the session ID will be persisted as a cookie. Consider the following example, in which two JSP files, say hello1.jsp and hello2.jsp, interac
t with each other. Basically, we create a new session within hello1.jsp and place an object within this session. The user can then traverse to hello2.jsp by clicking on the link present within the page.Within hello2.jsp, we simply extract the object that was earlier placed in the session and display its contents. Notice that we invoke the encodeURL() within hello1.jsp on the link used to invoke hello2.jsp; if cookies are disabled, the session ID is automatically appended to the URL, allowing hello2.jsp to still retrieve the session object. Try this example first with cookies enabled. Then disable cookie support, restart the brower, and try again. Each time you should see the maintenance of the session across pages. Do note that to get this example to work with cookies disabled at the browser, your JSP engine has to support URL rewriting.
<%@ page session=”true” %>
Integer num = new Integer(100);
String url =response.encodeURL(“hello2.jsp”);
<a href=’<%=url%>’>hello2.jsp</a>
<%@ page session=”true” %>
Integer i= (Integer )session.getValue(“num”);
out.println(“Num value in session is “+i.intValue());

Also Read:




This site uses Akismet to reduce spam. Learn how your comment data is processed.