Tuesday, May 27, 2008

Java Tricky Questions - 1

Whats the difference between

int length = 5;
int breadth = 10;
int area = length * breadth;

and

final int length = 5;
final int breadth = 10;
int area = length * breadth;


dont scroll down until you have thought over the answer
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
gave it a thought ?
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
sure ?
.
.
.
.
.
.
.
.
.
.
.
Ok then heres the answer...
In the second code snippet multiplication is done at compile time.
In first multiplication is done at Runtime.
Reason
Java compiler uses something known as Constant Folding. Constant folding refers to the compiler precalculating constant expressions.
Query
I wonder what will happen if the code is

int length = 5;
final int breadth = 10;
int area = length * breadth;

The above code will not use constant folding for length but do so for breadth.
What if ?

static final int breadth = 10;
int area = 5 * breadth;

then compiler will use constant folding for breadth.

Monday, May 26, 2008

HashMap : Not thread safe structure

Nice Read
http://pveentjer.wordpress.com/2008/05/26/hashmap-is-not-a-thread-safe-structure/

Java Tricky questions

Found this link
bad part is answers are not explained

http://www.mydeveloperconnection.com/html/JavaTrap.htm

All About Java Exceptions

Common Java wisdom gives us a few general principles about how to work with exceptions:

1. Don’t use exceptions for flow control and expected business situations, but only for exceptional situations
2. Use unchecked exceptions for programming errors, bugs, situations where the application or the current operation cannot expect to recover from.
3. Use checked exceptions for situations where the caller is expected to be able to make a full or partial recovery after the failure

If we keep the function return type as


public boolean doSomeWork()
{
if(success)
return true;
else
return false;
...
}


two probs
1) Caller will have to check the return value : if he doesnt he may continue with wrong assumption
2) The caller doesn’t have enough information to see what went wrong

With this kind of solution we are back to the way C programs were written... but remember this is java

Another way is...

public class SomeException extends RuntimeException
{
...
}
public boolean doSomeWork()
{
if(success)
return true;
else
throw new SomeException();
...
}


You may have to do some documentation for the new exception class. Which is a disadvantage if you are LAZY ;).
Else the advantages are
* If the client code fails to treat the exception at least the program doesn’t continue on a wrong path.
* We can send more information about the failure context in the exception class through the exception type and the exception instance content.
Disadvantages
* The client code programmer is not automatically warned to treat the exception


One more way is ...

public class SomeException extends Exception
{
...
}
public boolean doSomeWork() throws SomeException
{
if(success)
return true;
else
throw new SomeException();
...
}

Client code will use try / catch block

How can you catch multiple exceptions in java ??

Statement stmt = null;
try {
// do stuff that uses Statement instance
} catch (SQLException e) {
// handle state
log.error("Bad database", e);
} catch (NullPointerException e) {
// handle state
log.error("Bad parameter", e);
} catch (Exception e) {
// handle state
log.error("Bad luck", e);
} finally {
try {
stmt.close();
} catch (Exception ex) {}
}


Summary
Rule of thumb: Use Checked Exceptions for recoverable conditions and Runtime Exceptions for programming errors.
Checked exceptions are great in theory, but in practice lots of developers use them poorly and then the rest of us are left to clean up their mess.
checked exceptions are domain exceptions.

Links
http://truecode.blogspot.com/2008/01/bypassing-java-checked-exception.html
http://dev2dev.bea.com/pub/a/2006/11/effective-exceptions.html
http://dev2dev.bea.com/pub/a/2007/06/exception-advice.html
http://www.csd.uoc.gr/~andreou/

Thursday, May 22, 2008

JSF FAQs

JSF is MVC2 ?
As per my knowledge There is no MVC1 and MVC2
there is JSP model 1 and model 2 as explained in the article
http://www.javaworld.com/javaworld/jw-12-1999/jw-12-ssj-jspmvc.html
JSF is in the scope of model 2


Other frameworks like JSF ?
Apple's WebObjects is a similar architecture to JSF and so is ASP.net.

Difference betwwen managed beans and backing beans ??

f:facet ??


Advantages
JSF's fine-tuned event model allows your applications to be less tied to HTTP details and simplifies your development effort.


http://forum.java.sun.com/thread.jspa?threadID=674446

Tuesday, May 20, 2008

Servlets Basics

javax.servlet.http.HttpServlet Is an abstract class that extends the javax.servlet.GenericServlet class.
All the methods in it have protected identifier and the service method is overloaded

protected void service(HttpServletRequest req, HttpServletResponse resp)

Receives standard HTTP requests from the public service method and dispatches them to the doXXX methods defined in this class.

 void service(ServletRequest req, ServletResponse res)

Dispatches client requests to the protected service method.

Clicking on a hyperlink always sends a GET request and thus, the doGet() method of the servlet will be called. < href = " /servlet/TestServlet " method="POST"> Some URL < / a >
The method="POST" attribute-value pair does not make sense in the anchor tag.
Retrieve Request Parameter

String[ ] getParameterValues(String paramName)

The above method is for html element like dropbox etc
 Enumeration getParameterNames() 

This method is useful when you don’t know the names of the parameters. You can iterate through the Enumeration of Strings returned by this method and for each element you can call getParameter() or getParameterValues().

Retrieve request headers

There is one difference , though; unlike parameters, headers are specific to the HTTP protocol and so the methods that deal with the headers belong to HttpServletRequest and not to ServletRequest.

 String getHeader(String headerName) 

This method returns just one of the values associated with the given header.
 Enumeration getHeaderValues(String headerName)

This method returns all the values associated with the header as an Enumeration of String object.
 Enumeration getHeaderNames() 

This method is useful when you don’t know the names of the headers. You can iterate through the enumeration returned by this method, and for each element you can call getHeader() or getHeaderValues().

Which method would you use to retrieve the number of parameters present in a request?
Neither ServletRequest nor HttpServletRequest provides any method to retrieve the number of parameters directly. You’ll have to use ServletRequest.getParameterNames(), which returns an Enumeration, and count the number of parameters yourself.

GET vs POST



















































FEATURE

GET method

POST method

Type of data
text text & binary

Amount of data
Browser dependent gen is 255 unlimited

Visibility
data is part of URL Part of body not URL

Caching
can be cached cant be

Bookmarkable
Can bookmark Cant bookmark

Spl Case
Cant be used in case data is character set other than ASCII Can use any type of character set

Use Case
used when the form processing is "idempotent" used in all other cases

Default
Its default for HTML FORM element Its not .. need to use method attribute