interview questions

7
What are the ways to handle JSP exceptions? try-catch? Hmmm.. is there anything else? What is serialVersionUID and why is it important? Please show an example where missing serialVersionUID will cause a problem. The serialization runtime associates with each serializable class a version number, called a serialVersionUID, which is used during deserialization to verify that the sender and receiver of a serialized object have loaded classes for that object that are compatible with respect to serialization. If the receiver has loaded a class for the object that has a different serialVersionUID than that of the corresponding sender's class, then deserialization will result in an InvalidClassException. A serializable class can declare its own serialVersionUID explicitly by declaring a field named " serialVersionUID" that must be static, final, and of type long: ANY-ACCESS-MODIFIER static final long serialVersionUID = 42L ; If a serializable class does not explicitly declare a serialVersionUID, then the serialization runtime will calculate a default serialVersionUID value for that class based on various aspects of the class, as described in the Java(TM) Object Serialization Specification. However, it is strongly recommended that all serializable classes explicitly declare serialVersionUID values, since the default serialVersionUID computation is highly sensitive to class details that may vary depending on compiler implementations, and can thus result in unexpected InvalidClassExceptions during deserialization. Therefore, to guarantee a consistent serialVersionUID value across different java compiler implementations, a serializable class must declare an explicit serialVersionUID value. It is also strongly advised that explicit serialVersionUID declarations use the private modifier where possible, since such declarations apply only to the immediately declaring class--serialVersionUID fields are not useful as inherited members. What is the use of the finally block? Is finally block in Java guaranteed to be called? When finally block is NOT called?

Upload: auliya-sant

Post on 26-Sep-2015

212 views

Category:

Documents


0 download

DESCRIPTION

sdfdf

TRANSCRIPT

What are the ways to handle JSP exceptions? try-catch? Hmmm.. is there anything else?

What isserialVersionUIDand why is it important? Please show an example where missingserialVersionUIDwill cause a problem.

The serialization runtime associates with each serializable class a version number, called a serialVersionUID, which is used during deserialization to verify that the sender and receiver of a serialized object have loaded classes for that object that are compatible with respect to serialization. If the receiver has loaded a class for the object that has a different serialVersionUID than that of the corresponding sender's class, then deserialization will result in anInvalidClassException. A serializable class can declare its own serialVersionUID explicitly by declaring a field named "serialVersionUID" that must be static, final, and of typelong:

ANY-ACCESS-MODIFIER static final long serialVersionUID = 42L;

If a serializable class does not explicitly declare a serialVersionUID, then the serialization runtime will calculate a default serialVersionUID value for that class based on various aspects of the class, as described in the Java(TM) Object Serialization Specification. However, it isstrongly recommendedthat all serializable classes explicitly declare serialVersionUID values, since the default serialVersionUID computation is highly sensitive to class details that may vary depending on compiler implementations, and can thus result in unexpectedInvalidClassExceptionsduring deserialization. Therefore, to guarantee a consistent serialVersionUID value across different java compiler implementations, a serializable class must declare an explicit serialVersionUID value. It is also strongly advised that explicit serialVersionUID declarations use the private modifier where possible, since such declarations apply only to the immediately declaring class--serialVersionUID fields are not useful as inherited members.

What is the use of the finally block? Is finally block in Java guaranteed to be called? When finally block is NOT called?

The finally block always executes when the try block exits. This ensures that the finally block is executed even if an unexpected exception occurs. But finally is useful for more than just exception handling it allows having cleanup code accidentally bypassed by a return, continue, or break. Putting cleanup code in a finally block is always a good practice, even when no exceptions are anticipated.

If the JVM exits while the try or catch code is being executed, then the finally block may not execute. Likewise, if the thread executing the try or catch code is interrupted or killed, the finally block may not execute even though the application as a whole continues.

Why there are two Date classes; one in java.util package and another in java.sql?

A java.util.Date represents date and time of day, a java.sql.Date only represents a date. The complement of java.sql.Date is java.sql.Time, which only represents a time of day.The java.sql.Date is a subclass (an extension) of java.util.Date. So, what changed in java.sql.Date:

-- toString() generates a different string representation: yyyy-mm-dd-- a static valueOf(String) methods to create a Date from a String with above representation-- the getters and setter for hours, minutes and seconds are deprecated

The java.sql.Date class is used with JDBC and it was intended to not have a time part, that is, hours, minutes, seconds, and milliseconds should be zero but this is not enforced by the class.

Question : What will happen if you put return statement or System.exit () on try or catch block ? Will finally block execute?

This is a verypopular tricky Java questionand its tricky because many programmer think that no matter what, but finally block will always execute. This question challenge that misconcept by puttingreturnstatement in try or catch block or callingSystem.exitfrom try or catch block. Answer of this tricky question in Java is thatfinallyblock will execute even if you putreturnstatement in try block or catch block but finally block won't run if you callSystem.exitform try or catch.

What is the difference between SOAP-based web services and REST-based web services?

Give an overview of how Spring Dependency Injection container works. What is the purpose of DI?

1> I have below class

class CricketTeam{

String name; //this is the complete name(inclusive of first and last name)

}

Cricket Players name are as below:

1> Sachin Tendulkar

2> Gautam Gambhir

3> Ricky Ponting

4> Shahid Afridi

5> Kevin Pieterson

6> MS Dhoni

I want to sort the above Cricket Players name by their last name only.Suugestions/code provided would be appreciated.

2> what are the advantages of using enhanced for loop against iterator in java.what are the advantages of using enhanced for loop in java and why was it introduced in java at the first place when the iterator could do the job.?

1. Implement aComparatorwhich parses the last name out of player names and compares these, then sort the collection of cricket players using that comparator.A simplistic example (without error handling, and assuming all players have exactly one first name and no middle name):

2. class CricketTeamComparator implements Comparator {

3. @Override

4. public int compare(CricketTeam o1, CricketTeam o2) {

5. String lastName1 = o1.name.split(" ")[1];

6. String lastName2 = o2.name.split(" ")[1];

7. return lastName1.compareTo(lastName2);

8. }

9. }

10.

11. ...

12.

13. List team = new ArrayList();

14. ...

Collections.sort(team, new CricketTeamComparator());

15. it is cleaner, more concise and safer (e.g. avoids specific subtle bugs in multiple embedded loops, when the iterator is accidentally incremented too often by callingnext()too many times).Code sample (fromEffective Java 2nd Edition, Item 46:Prefer for-each loops to traditional for loops):

16. // Can you spot the bug?

17. enum Suit { CLUB, DIAMOND, HEART, SPADE }

18. enum Rank { ACE, DEUCE, THREE, FOUR, FIVE, SIX, SEVEN, EIGHT,

19. NINE, TEN, JACK, QUEEN, KING }

20. ...

21. Collection suits = Arrays.asList(Suit.values());

22. Collection ranks = Arrays.asList(Rank.values());

23. List deck = new ArrayList();

24. for (Iterator i = suits.iterator(); i.hasNext(); )

25. for (Iterator j = ranks.iterator(); j.hasNext(); )

deck.add(new Card(i.next(), j.next()));

List team;

Collections.sort(team, new Comparator) {

int compare(CricketTeam o1, CricketTeam o2) {

return o1.name.split(" ")[1].compareTo(o2.name.split(" ")[1])

}

}

When to use LinkedList over ArrayList?

What is 'System', 'out', 'println' in System.out.println ?

Systemis a class in the java.lang package.outis a static member of theSystemclass, and is an instance of java.io.PrintStream .printlnis a method of java.io.PrintStream . This method is overloaded to print message to output destination, which is typically a console or file.

What are the advantages of using JDBC's Prepared Statements?

Precompilation and DB-side caching of the SQL statement leads to overall faster execution and the ability to reuse the same SQL statement inbatches.

Automatic prevention ofSQL injectionattacksby builtin escaping of quotes and other special characters. Note that this requires that you use any of thePreparedStatementsetXxx()methods to set the values

The Prepared Statement is a slightly more powerful version of a Statement, and should always be at least as quick and easy to handle as a Statement.The Prepared Statement may be parametrized

Most relational databases handles a JDBC / SQL query in four steps:1.Parse the incoming SQL query2. Compile the SQL query3. Plan/optimize the data acquisition path4. Execute the optimized query / acquire and return data

A Statement will always proceed through the four steps above for each SQL query sent to the database. A Prepared Statement pre-executes steps (1) - (3) in the execution process above. Thus, when creating a Prepared Statement some pre-optimization is performed immediately. The effect is to lessen the load on the database engine at execution time.

Some of the benefits of PreparedStatement over Statement are:

1. PreparedStatement helps us in preventing SQL injection attacks because it automatically escapes the special characters.

2. PreparedStatement allows us to execute dynamic queries with parameter inputs.

3. PreparedStatement provides different types of setter methods to set the input parameters for the query.

4. PreparedStatement is faster than Statement. It becomes more visible when we reuse the PreparedStatement or use its batch processing methods for executing multiple queries.

5. PreparedStatement helps us in writing object Oriented code with setter methods whereas with Statement we have to use String Concatenation to create the query. If there are multiple parameters to set, writing Query using String concatenation looks very ugly and error prone.

Q) What is the difference between final, finally and finalize() in Java?

Ans)

final- A final variable acts as a constant, a final class is immutable and a final method cannot be ovrriden while doing inheritance.

finally- handles exception. The finally block is optional and provides a mechanism to clean up regardless of what happens within the try block (except System.exit(0) call). Use the finally block to close files or to release other system resources like database connections, statements etc.

finalize()- method belongs to Object class. The method that is invoked while doing the garbage collection of the object. It could be used for allowing it to clean up its state. Good use cases will be to free connection pools , deallocate resources etc.

What was the most exciting project for you in your 10 years of career? What were your responsibilities in that project?

If your manager assigns you a project of your capacity How comfortable you are as an individual player?

How can we handle error and exception on a JSP page ?

Q14. Is there any difference between body onload() and document.ready() function?

Ans:document.ready()function is different from bodyonload()function for 2 reasons.

1. We can have more than onedocument.ready()function in a page where we can have only one bodyonloadfunction.

2. document.ready()function is called as soon as DOM is loaded wherebody.onload()function is called when everything gets loaded on the page that includes DOM, images and all associated resources of the page.