Tuesday, November 10, 2009

JSP

What is JSP? Describe its concept
JSP is a technology that combines HTML/XML markup languages and elements of Java programming Language to return dynamic content to the Web client, It is normally used to handle Presentation logic of a web application, although it may have business logic.

What are the lifecycle phases of a JSP?
JSP page looks like a HTML page but is a servlet. When presented with JSP page the JSP engine does the following 7 phases.
  1. Page translation: -page is parsed, and a java file which is a servlet is created.
  2. Page compilation: page is compiled into a class file
  3. Page loading : This class file is loaded.
  4. Create an instance :- Instance of servlet is created
  5. jspInit() method is called
  6. _jspService is called to handle service calls
  7. _jspDestroy is called to destroy it when the servlet is not required.


What is a translation unit?
JSP page can include the contents of other HTML pages or other JSP files. This is done by using the include directive. When the JSP engine is presented with such a JSP page it is converted to one servlet class and this is called a translation unit, Things to remember in a translation unit is that page directives affect the whole unit, one variable declaration cannot occur in the same unit more than once, the standard action jsp:useBean cannot declare the same bean twice in one unit.

How is JSP used in the MVC model
JSP is usually used for presentation in the MVC pattern (Model View Controller ) i.e. it plays the role of the view. The controller deals with calling the model and the business classes which in turn get the data, this data is then presented to the JSP for rendering on to the client.

What are context initialization parameters
Context initialization parameters are specified by the in the web.xml file, these are initialization parameter for the whole application and not specific to any servlet or 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 un-interpreted 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.

What is a Hidden Comment
A comment 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.

What is a Expression
Expressions are act as place holders for language expression, expression is evaluated each time the page is accessed.

What is a Declaration
It 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 semicolons separate them. 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 declare variables or methods to use later in the file, write expressions valid in the page scripting language, use any of the JSP implicit objects or any object declared with a .

What are the 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 are:
  1. request
  2. response
  3. pageContext
  4. session
  5. application
  6. out
  7. config
  8. page
  9. exception


What’s the 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 completely with in the web container And then returns to the calling method. When a sendRedirect 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 completely 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 values for the
The different scope values for are:
  1. page
  2. request
  3. session
  4. application


Why are JSP pages the preferred API for creating a web-based client program
Because no plug-ins or security policy files are needed on the client systems(applet does). Also, JSP pages enable cleaner and more module application design because they provide a way to separate applications programming from web page design. This means personnel involved in web page design do not need to understand Java programming language syntax to do their jobs.

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

What is difference between custom JSP tags and beans
Custom JSP tag is a tag you defined. You define how a tag, its attributes and its body are interpreted, and then group your tags into collections called tag libraries that can be used in any number of JSP files. Custom tags and beans accomplish the same goals — encapsulating complex behavior into simple and accessible forms. There are several differences:
  • Custom tags can manipulate JSP content; beans cannot.
  • Complex operations can be reduced to a significantly simpler form with custom tags than with beans.
  • Custom tags require quite a bit more work to set up than do beans.
  • Custom tags usually define relatively self-contained behavior, whereas beans are often defined in one servlet and used in a different servlet or JSP page.
  • Custom tags are available only in JSP 1.1 and later, but beans can be used in all JSP 1.x versions.


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

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.

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
%>

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:

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

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.

value="<%=java.text.DateFormat.getDateInstance().format(new java.util.Date()) %>"/ >
<%-- scriptlets calling bean setter methods go here --%>"

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, interact 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.
hello1.jsp
<%@ page session="true" %>
<%
Integer num = new Integer(100);
session.putValue("num",num);
String url =response.encodeURL("hello2.jsp");
%>
hello2.jsp
<%@ page session="true" %>
<%
Integer i= (Integer )session.getValue("num");
out.println("Num value in session is "+i.intValue());

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
file1.jsp:
<%@page contentType="text/html"%>
<%!
public void test(JspWriter writer) throws IOException{
writer.println("Hello!");
}
%>
file2.jsp
<%@include file="file1.jsp"%>


<%test(out);% >



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:
<%
session.setMaxInactiveInterval(300);
%>
would reset the inactivity period for this session to 5 minutes. The inactivity interval is set in seconds.

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");
response.addCookie(mycookie);
//delete a cookie
Cookie killMyCookie = new Cookie("mycookie", null);
killMyCookie.setMaxAge(0);
killMyCookie.setPath("/");
response.addCookie(killMyCookie);
%>

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");
f.setName(request.getParameter("name"));
f.setAddr(request.getParameter("addr"));
f.setAge(request.getParameter("age"));
//use the id to compute
//additional bean properties like info
//maybe perform a db query, etc.
// . . .
f.setPersonalizationInfo(info);
request.setAttribute("fBean",f);
getServletConfig().getServletContext().getRequestDispatcher
("/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" class="govi.FormBean" 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" /

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" %>

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
" >

How can I get to print the stacktrace for an exception occuring within my JSP page
By printing out the exception’s stack trace, you can usually diagonse a problem better when debugging JSP pages. By looking at a stack trace, a programmer should be able to discern which method threw the exception and which method called that method. However, you cannot print the stacktrace using the JSP out implicit variable, which is of type JspWriter. You will have to use a PrintWriter object instead. The following snippet demonstrates how you can print a stacktrace from within a JSP error page:
<%@ page isErrorPage="true" %>
<%
out.println(" ");
PrintWriter pw = response.getWriter();
exception.printStackTrace(pw);
out.println(" ");
%>

How do you pass an InitParameter to a JSP
The JspPage interface defines the jspInit() and jspDestroy() method which the page writer can use in their pages and are invoked in much the same manner as the init() and destory() methods of a servlet. The example page below enumerates through all the parameters and prints them to the console.
<%@ page import="java.util.*" %>
<%!
ServletConfig cfg =null;
public void jspInit(){
ServletConfig cfg=getServletConfig();
for (Enumeration e=cfg.getInitParameterNames(); e.hasMoreElements();) {
String name=(String)e.nextElement();
String value = cfg.getInitParameter(name);
System.out.println(name+"="+value);
}
}
%>

How can my JSP page communicate with an EJB Session Bean
The following is a code snippet that demonstrates how a JSP page can interact with an EJB session bean:
<%@ page import="javax.naming.*, javax.rmi.PortableRemoteObject, foo.AccountHome, foo.Account" %>
<%!
//declare a "global" reference to an instance of the home interface of the session bean
AccountHome accHome=null;
public void jspInit() {
//obtain an instance of the home interface
InitialContext cntxt = new InitialContext( );
Object ref= cntxt.lookup("java:comp/env/ejb/AccountEJB");
accHome = (AccountHome)PortableRemoteObject.narrow(ref,AccountHome.class);
}
%>
<%
//instantiate the session bean
Account acct = accHome.create();
//invoke the remote methods
acct.doWhatever(...);
// etc etc...
%>

Can we implement an interface in a JSP
No

What is the difference between ServletContext and PageContext
ServletContext: Gives the information about the container. PageContext: Gives the information about the Request

What is the difference in using request.getRequestDispatcher() and context.getRequestDispatcher()
request.getRequestDispatcher(path): In order to create it we need to give the relative path of the resource,
context.getRequestDispatcher(path): In order to create it we need to give the absolute path of the resource.

How to pass information from JSP to included JSP
Using <%jsp:param> tag.

What is the difference between directive include and jsp include
<%@ include>: Used to include static resources during translation time. JSP include: Used to include dynamic content or static content during runtime.

What is the difference between RequestDispatcher and sendRedirect
RequestDispatcher: server-side redirect with request and response objects. sendRedirect : Client-side redirect with new request and response objects.

How do I mix JSP and SSI #include
If you're just including raw HTML, use the #include directive as usual inside your .jsp file.

But it's a little trickier if you want the server to evaluate any JSP code that's inside the included file. If your data.inc file contains jsp code you will have to use
<%@ vinclude="data.inc" %>
The is used for including non-JSP files.

Design Patterns Interview Questions

Creational patterns Structural patterns Behavioral pattern J2EE patterns
Abstract Factory Adapter Chain of Responsibility
MVC
Builder Bridge Command Business Delegate
Factory method Composite Interpreter Composite Entity
Prototype Decorator Iterator Data Access Object
Singleton Façade
Mediator Front Controller

Flyweight Memento Intercepting Filter

Proxy Observer Service Locator


State Transfer Object


Strategy


Template Method



Visitor

Singleton Pattern



Define Singleton pattern
One instance of a class or one value accessible globally in an application.

Where to use & benefits
Ensure unique instance by defining class final to prevent cloning.
May be extensible by the subclass by defining subclass final.
Make a method or a variable public or/and static.
Access to the instance by the way you provided.
Well control the instantiation of a class.
Define one value shared by all instances by making it static.

Related patterns include
  • Abstract factory, which is often used to return unique objects.
  • Builder, which is used to construct a complex object, whereas a singleton is used to create a globally accessible object.
  • Prototype, which is used to copy an object, or create an object from its prototype, whereas a singleton is used to ensure that only one prototype is guaranteed.


Example of Singleton Pattern
One file system, one window manager, one printer spooler, one Test engine, one Input/Output socket and etc.

To design a Singleton class, you may need to make the class final like java.Math, which is not allowed to subclass, or make a variable or method public and/or static, or make all constructors private to prevent the compiler from creating a default one.

For example, to make a unique remote connection,

final class RemoteConnection {
private Connect con;
private static RemoteConnection rc = new RemoteConnection(connection);
private RemoteConnection(Connect c) {
con = c;
....
}
public static RemoteConnection getRemoteConnection() {
return rc;
}
public void setConnection(Connect c) {
this(c);
}
}

usage:
RemoteConnection rconn = RemoteConnection.getRemoteConnection;
rconn.loadData();
...


The following statement may fail because of the private constructor
RemoteConnection con = new RemoteConnection(connection); //failed

//failed because you cannot subclass it (final class)
class Connection extends RemoteConnection {}

For example, to use a static variable to control the instance;

class Connection {
public static boolean haveOne = false;
public Connection() throws Exception{
if (!haveOne) {
doSomething();
haveOne = true;
}else {
throw new Exception("You cannot have a second instance");
}
}
public static Connection getConnection() throws Exception{
return new Connection();
}
void doSomething() {}
//...
public static void main(String [] args) {
try {
Connection con = new Connection(); //ok
}catch(Exception e) {
System.out.println("first: " +e.getMessage());
}
try {
Connection con2 = Connection.getConnection(); //failed.
}catch(Exception e) {
System.out.println("second: " +e.getMessage());
}
}
}

C:\\ Command Prompt
C:\\> java Connection
second: You cannot have a second instance




For example to use a public static variable to ensure a unique.

class Employee {
public static final int companyID = 12345;
public String address;
//...

}
class HourlyEmployee extends Employee {
public double hourlyRate;
//....
}
class SalaryEmployee extends Employee {
public double salary;
//...
}
class Test {
public static void main(String[] args) {
Employee Evens = new Employee();
HourlyEmployee Hellen = new HourlyEmployee();
SalaryEmployee Sara = new SalaryEmployee();
System.out.println(Evens.companyID == Hellen.companyID); //true
System.out.println(Evens.companyID == Sara.companyID); //true
}
}

Output :
true
true


The companyID is a unique and cannot be altered by all subclasses.

Note that Singletons are only guaranteed to be unique within a given class
loader. If you use the same class across multiple distinct enterprise
containers, you'll get one instance for each container.

Saturday, November 7, 2009

Core Java FAQs

CORE JAVA!

Language Fundamentals

How many number of non-public class definitions can a source file have
A source file can contain unlimited number of non-public class definitions
List primitive data types, there size and there range (min, max)
Data Type Bytes bits min max
boolean
-
1
-
-
char
2
16
0
2^16-1
byte
1
8
-2^7
2^7-1
short
2
16
-2^15 2^15-1
int
4
32
-2^31 2^31-1
long
8
64
-2^63 2^63-1
float
4
32
-
-
double
8
64
-
-


What types of values does boolean variables take
It only takes values true and false

Which primitive datatypes are signed
All except char and Boolean

Is char type signed or unsigned
char type is integral but unsigned. It range is 0 to 2^7-1

What forms an integral literal can be
decimal, octal and hexadecimal, hence example it can be 28, 034 and 0x1c respectively

What is the default value of Boolean
False

Why is the main method static
So that it can be invoked without creating an instance of that class

What is the difference between class variable, member variable and automatic(local) variable
class variable is a static variable and does not belong to instance of class but rather shared across all the instances
member variable belongs to a particular instance of class and can be called from any method of the class
automatic or local variable is created on entry to a method and has only method scope

When are static and non static variables of the class initialized
The static variables are initialized when the class is loadedNon static variables are initialized just before the constructor is called

When are automatic variable initialized
Automatic variable have to be initialized explicitly

How is an argument passed in java, by copy or by reference
If the variable is primitive datatype then it is passed by copy.
If the variable is an object then it is passed by reference

What is garbage collection
The runtime system keeps track of the memory that is allocated and is able to determine whether that memory is still useable. This work is usually done in background by a low-priority thread that is referred to as garbage collector. When the gc finds memory that is no longer accessible from any live thread it takes steps to release it back to the heap for reuse

Does System.gc and Runtime.gc() guarantee garbage collection
No

Operators and assignment

What are different types of operators in java
Uniary ++, --, +, -, |, ~, ()
Arithmetic *, /, %,+, -
Shift <<, >>, >>>
Comparison =, instanceof, = =,!=Bitwise &, ^, |Short Circuit &&, ||Ternary ?:Assignment =

How does bitwise (~) operator work
It converts all the 1 bits in a binary value to 0s and all the 0 bits to 1s, e.g 11110000 coverts to 00001111

What is a modulo operator %
This operator gives the value which is related to the remainder of a divisione.g x=7%4 gives remainder 3 as an answer

Can shift operators be applied to float types.
No, shift operators can be applied only to integer or long types

What happens to the bits that fall off after shifting
They are discarded

What values of the bits are shifted in after the shift
In case of signed left shift >> the new bits are set to zero

But in case of signed right shift it takes the value of most significant bit before the shift, that is if the most significant bit before shift is 0 it will introduce 0, else if it is 1, it will introduce 1

Modifiers

What are access modifiers
These public, protected and private, these can be applied to class, variables, constructors and methods. But if you don’t specify an access modifier then it is considered as Friendly

Can protected or friendly features be accessed from different packages
No when features are friendly or protected they can be accessed from all the classes in that package but not from classes in another package

How can you access protected features from another package
You can access protected features from other classes by subclassing the that class in another package, but this cannot be done for friendly features

What are the rules for overriding
Private method can be overridden by private, friendly, protected or public methods
Friendly method can be overridden by friendly, protected or public methods
Protected method can be overridden by protected or public methods
Public method can be overridden by public method

Explain modifier final
Final can be applied to classes, methods and variables and the features cannot be changed. Final class cannot be subclassed, methods cannot be overridden

Can you change the reference of the final object
No the reference cannot be change, but the data in that object can be changed

Can abstract modifier be applied to a variable
No it is applied only to class and methods

Can abstract class be instantiated
No abstract class cannot be instantiated i.e you cannot create a new object of this class

When does the compiler insist that the class must be abstract
If one or more methods of the class are abstract.
If class inherits one or more abstract methods from the parent abstract class and no implementation is provided for that method
If class implements an interface and provides no implementation for those methods

How is abstract class different from final class
Abstract class must be subclassed and final class cannot be subclassed

Where can static modifiers be used
They can be applied to variables, methods and even a block of code, static methods and variables are not associated with any instance of class

When are the static variables loaded into the memory
During the class load time

When are the non static variables loaded into the memory
They are loaded just before the constructor is called

How can you reference static variables
Via reference to any instance of the class
Computer comp = new Computer ();
comp.harddisk where hardisk is a static variable
comp.compute() where compute is a method

Via the class name

Computer.harddisk
Computer.compute()
Can static method use non static features of there class
No they are not allowed to use non static features of the class, they can only call static methods and can use static data

What is static initializer code
A class can have a block of initializer code that is simply surrounded by curly braces and labeled as static e.g.
public class Demo{
static int =10;
static{
System.out.println(“Hello world’);
}
}

And this code is executed exactly once at the time of class load

Where is native modifier used
It can refer only to methods and it indicates that the body of the method is to be found else where and it is usually written in non java language

What are transient variables
A transient variable is not stored as part of objects persistent state and they cannot be final or static

What is synchronized modifier used for
It is used to control access of critical code in multithreaded programs

What are volatile variables
It indicates that these variables can be modified asynchronously

Conversion Casting and Promotion

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

What are the four general cases for Conversion and Casting
Conversion of primitives
Casting of primitives
Conversion of object references
Casting of object references

When can conversion happen
It can happen during
Assignment
Method call
Arithmetic promotion
What are the rules for primitive assignment and method call conversion
A boolean can not be converted to any other type
A non Boolean can be converted to another non boolean type, if the conversion is widening conversion
A non Boolean cannot be converted to another non boolean type, if the conversion is narrowing conversion
See figure below for simplicity
assignment

What are the rules for primitive arithmetic promotion conversion
For Unary operators :
If operant is byte, short or a char it is converted to an int
If it is any other type it is not converted

For binary operands :

If one of the operands is double, the other operand is converted to double
Else If one of the operands is float, the other operand is converted to float
Else If one of the operands is long, the other operand is converted to long
Else both the operands are converted to int


What are the rules for casting primitive types
You can cast any non Boolean type to any other non boolean type
You cannot cast a boolean to any other type; you cannot cast any other type to a boolean

What are the rules for object reference assignment and method call conversion
An interface type can only be converted to an interface type or to object. If the new type is an interface, it must be a superinterface of the old type
A class type can be converted to a class type or to an interface type. If converting to a class type the new type should be superclass of the old type. If converting to an interface type new type the old class must implement the interface
An array maybe converted to class object, to the interface cloneable, or to an array. Only an array of object references types may be converted to an array, and the old element type must be convertible to the new element

What are the rules for Object reference casting
Casting from Old types to Newtypes
Compile time rules
  • When both Oldtypes and Newtypes are classes, one should be subclass of the other
  • When both Oldtype ad Newtype are arrays, both arrays must contain reference types (not primitive), and it must be legal to cast an element of Oldtype to an element of Newtype
  • You can always cast between an interface and a non-final object

Runtime rules

  • If Newtype is a class. The class of the expression being converted must be Newtype or must inherit from Newtype
  • If NewType is an interface, the class of the expression being converted must implement Newtype


Flow Control and exception

What is the difference between while and do while loop
Do while loop walways executes the body of the loop at least once, since the test is performed at the end of the body

When do you use continue and when do you use break statements
When continue statement is applied it prematurely completes the iteration of a loop.
When break statement is applied it causes the entire loop to be abandoned.

What is the base class from which all exceptions are subclasses
All exceptions are subclasses of a class called java.lang.Throwable

How do you intercept and thereby control exceptions
We can do this by using try/catch/finally blocks
You place the normal processing code in try block
You put the code to deal with exceptions that might arise in try block in catch block
Code that must be executed no matter what happens must be place in finally block

When do we say an exception is handled
When an exception is thrown in a try block and is caught by a matching catch block, the exception is considered to have been handled

When do we say an exception is not handled
There is no catch block that names either the class of exception that has been thrown or a class of exception that is a parent class of the one that has been thrown, then the exception is considered to be unhandled, in such condition the execution leaves the method directly as if no try has been executed

In what sequence does the finally block gets executed
If you put finally after a try block without a matching catch block then it will be executed after the try block
If it is placed after the catch block and there is no exception then also it will be executed after the try block
If there is an exception and it is handled by the catch block then it will be executed after the catch block

What can prevent the execution of the code in finally block
  • The death of thread
  • Use of system.exit()
  • Turning off the power to CPU
  • An exception arising in the finally block itself
What are the rules for catching multiple exceptions
A more specific catch block must precede a more general one in the source, else it gives compilation error
Only one catch block, that is first applicable one, will be executed

What does throws statement declaration in a method indicate
This indicates that the method throws some exception and the caller method should take care of handling it

What are checked exception
Checked exceptions are exceptions that arise in a correct program, typically due to user mistakes like entering wrong data or I/O problems

What are runtime exceptions
Runtime exceptions are due to programming bugs like out of bond arrays or null pointer exceptions.

What is difference between Exception and errors
Errors are usually compile time and exceptions can be runtime or checked

How will you handle the checked exceptions
You can provide a try/catch block to handle it. OR
Make sure method declaration includes a throws clause that informs the calling method an exception might be thrown from this particular method
When you extend a class and override a method, can this new method throw exceptions other than those that were declared by the original method
No it cannot throw, except for the subclasses of those exceptions

Is it legal for the extending class which overrides a method which throws an exception, not o throw in the overridden class
Yes it is perfectly legal

Explain the user defined Exceptions?
User defined Exceptions are the separate Exception classes defined by the user for specific purposed. An user defined can created by simply sub-classing it to the Exception class. This allows custom exceptions to be generated (using throw) and caught in the same way as normal exceptions.
Example:
class myCustomException extends Exception {
// The class simply has to exist to be an exception
}

Objects and Classes

What's the difference between constructors and other methods
Constructors must have the same name as the class and can not return a value. They are only called once while regular methods could be called many times.

What is the difference between Overloading and Overriding
Overloading : Reusing the same method name with different arguments and perhaps a different return type is called as overloading
Overriding : Using the same method name with identical arguments and return type is know as overriding

What do you understand by late binding or virtual method Invocation. (Example of runtime polymorphism)
When a compiler for a non object oriented language comes across a method invocation, it determines exactly what target code should be called and build machine language to represent that call. In an object oriented language, this is not possible since the proper code to invoke is determined based upon the class if the object being used to make the call, not the type of the variable. Instead code is generated that will allow the decision to be made at run time. This delayed decision making is called as late binding

Can overriding methods have different return types
No they cannot have different return types

If the method to be overridden has access type protected, can subclass have the access type as private
No, it must have access type as protected or public, since an overriding method must not be less accessible than the method it overrides

Can constructors be overloaded
Yes constructors can be overloaded

What happens when a constructor of the subclass is called
A constructor delays running its body until the parent parts of the class have been initialized. This commonly happens because of an implicit call to super() added by the compiler. You can provide your own call to super(arguments..) to control the way the parent parts are initialized. If you do this, it must be the first statement of the constructor.

If you use super() or this() in a constructor where should it appear in the constructor
It should always be the first statement in the constructor

What is an inner class
An inner class is same as any other class, but is declared inside some other class

How will you reference the inner class
To reference it you will have to use OuterClass$InnerClass

Can objects that are instances of inner class access the members of the outer class
Yes they can access the members of the outer class

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

Can inner classes be static
Yes inner classes can be static, but they cannot access the non static data of the outer classes, though they can access the static data

Can an inner class be defined inside a method
Yes it can be defined inside a method and it can access data of the enclosing methods or a formal parameter if it is final

What is an anonymous class
Some classes defined inside a method do not need a name, such classes are called anonymous classes

What are the rules of anonymous class
The class is instantiated and declared in the same place
The declaration and instantiation takes the form
new Xxxx () {// body}
Where Xxxx is an interface name.
An anonymous class cannot have a constructor. Since you do not specify a name for the class, you cannot use that name to specify a constructor

Threads

Where does java thread support reside
It resides in three places
The java.lang.Thread class (Most of the support resides here)
The java.lang.Object class
The java language and virtual machine


What is the difference between Thread and a Process
Threads run inside process and they share data.
One process can have multiple threads, if the process is killed all the threads inside it are killed, they dont share data

What happens when you call the start() method of the thread
This registers the thread with a piece of system code called thread scheduler
The schedulers determines which thread is actually running

Does calling start () method of the thread causes it to run
No it merely makes it eligible to run. The thread still has to wait for the CPU time along with the other threads, then at some time in future, the scheduler will permit the thread to run

When the thread gets to execute, what does it execute
The thread executes a method call run(). It can execute run() method of either of the two choices given below :
The thread can execute it own run() method.
The thread can execute the run() method of some other objects
For the first case you need to subclass the Thread class and give your subclass a run() method
For the second method you need to have a class implement the interface runnable. Define your run method. Pass this object as an argument to the Thread constructor

How many methods are declared in the interface runnable
The runnable method declares only one method :
public void run();

Which way would you prefer to implement threading , by extending Thread class or implementing Runnable interface
The preferred way will be to use Interface Runnable, because by subclassing the Thread class you have single inheritance i.e you wont be able to extend any other class

What happens when the run() method returns
When the run() method returns, the thread has finished its task and is considered dead. You can’t restart a dead thread. You can call the methods of dead thread

What are the different states of the thread
They are as follows:
Running: The state that all thread aspire to be
Various waiting states : Waiting, Sleeping, Suspended and Bloacked
Ready : Waiting only for the CPU
Dead : All done


What is Thread priority
Every thread has a priority, the higher priorit thread gets preference over the lower priority thread by the thread scheduler

What is the range of priority integer
It is from 1 to 10. 10 beings the highest priority and 1 being the lowest

What is the default priority of the thread
The default priority is 5

What happens when you call Thread.yield()
It caused the currently executing thread to move to the ready state if the scheduler is willing to run any other thread in place of the yielding thread.
Yield is a static method of class Thread

What is the advantage of yielding
It allows a time consuming thread to permit other threads to execute

What happens when you call Thread.sleep()
It passes time without doing anything and without using the CPU. A call to sleep method requests the currently executing thread to cease executing for a specified amount of time.

Does the thread method start executing as soon as the sleep time is over
No, after the specified time is over the thread enters into ready state and will only execute when the scheduler allows it to do so.

What do you mean by thread blocking
If a method needs to wait an indeterminable amount of time until some I/O occurrence takes place, then a thread executing that method should graciously step out of the Running state. All java I/O methods behave this way. A thread that has graciously stepped out in this way is said to be blocked

What threading related methods are there in object class
wait(), notify() and notifyAll() are all part of Object class and they have to be called from synchronized code only

What is preemptive scheduling
In preemptive scheduling there are only two ways for the thread to leave the running state without ecplicitly calling wait() or suspended()
It can cease t be ready to execute ()by calling a blocking I/O method)
It can get moved out by CPU by a higher priorit thread that becomes ready to execute

What is non-preemptive or Time sliced or round robin scheduling
With time slicing the thread is allowd to execute for a limited amount of time. It is then moved to ready state, where it must contend with all the other ready threads.

What are the two ways of synchronizing the code
Synchronizing an entire method by putting the synchronized modifier in the methods declaration. To execute the method, a thread must acquire the lock of the object that owns the method

Synchronize a subset of a method by surrounding the desired lines of code with curly brackets and inserting the synchronized expression before the opening curly. This allows you to synchronize the block on the lock of any object at all, not necessarily the object that owns the code

What happens when the wait() method is called
The calling thread gives up CPU
The calling thread gives up the lock
The calling thread goes into the monitor’s waiting pool

What happens when the notify() method is called
One thread gets moved out of monitors waiting pool and into the ready state
The thread that was notified ust reacquire the monitors locl before it can proceed

Using notify () method how you can specify which thread should be notified
You cannot specify which thread is to be notified, hence it is always better to call notifyAll() method

java.lang & java.util Packages


What is the ultimate ancestor of all java classes
Object class is the ancestor of all the java classes

What are important methods of Object class
wait(), notify(), notifyAll(), equals(), toString().

What is the difference between “= =” and “equals()”
“= =” does shallow comparison, It retuns true if the two object points to the same address in the memory, i.e if the same the same reference
“equals()” does deep comparison, it checks if the values of the data in the object are same

What would you use to compare two String variables - the operator == or the method equals()?
I'd use the method equals() to compare the values of the Strings and the == to check if two variables point at the same instance of a String object

Give example of a final class
Math class is final class and hence cannot be extended

What is the difference between String and StringBuffer
String is an immutable class, i.e you cannot change the values of that class
Example :
String str = “java”; // address in memory say 12345
And now if you assign a new value to the variable str then
str = “core java”; then the value of the variable at address 12345 will not change but a new memory is allocated for this variable say 54321
So in the memory address 12345 will have value “java”
And the memory address 54321 will have value “core java” and the variable str will now be pointing to address 54321 in memory

StringBuffer can be modified dynamically
Example:
StringBuffer strt =”java” // address in memory is say 12345
And now if you assign a new value to the variable str then
Str = “core java”; then value in the address of memory will get replaced, a new memory address is not allocated in this case.

What will be the result if you compare StringBuffer with String if both have same values
It will return false as you cannot compare String with StringBuffer

What is Collection API
The Collection API is a set of classes and interfaces that support operation on collections of objects. These classes and interfaces are more flexible, more powerful, and more regular than the vectors, arrays, and hashtables if effectively replaces.
Example of classes: HashSet, HashMap, ArrayList, LinkedList, TreeSet and TreeMap.
Example of interfaces: Collection, Set, List and Map.

What are different types of collections
A collection has no special order and does not reject duplicates
A list is ordered and does not reject duplicates
A set has no special order but rejects duplicates
A map supports searching on a key field, values of which must be unique

Tell me something about Arrays
Arrays are fast to access, but are inefficient if the number of elements grow and if you have to insert or delete an element

Difference between ArrayList and Vector
Vector methods are synchronized while ArrayList methods are not

Iterator a Class or Interface? What is its use?
Iterator is an interface which is used to step through the elements of a Collection

Difference between Hashtable and HashMap
Hashtable does not store null value, while HashMap does
Hashtable is synchronized, while HashMap is not

This site will be helpful for someone looking for a new job or a promotion or someone looking to brush up few topics if they are moving to new project and have not been quite in touch with one of the technologies; it will also help freshers to understand the basics of java. I strongly recommend they thoroughly go through the Core java page before proceeding with advance topics.

For being a successful java software professional, one has to have the knowledge of following things
  • Java Language (J2EE included)
  • One Database (Can be anything like oracle, sybase, etc)
  • One Application server (Weblogic, Webserver, etc)
  • One Scripting language like Java Script


This site will cover all the above topics, If any topic is not there yet, don't worry it is coming soon, except the Scripting language, since there are already too many website dedicated for it.

As the site grows there will be many more topics added to the site; so please subscribe to our regular newsletter, as it will help you remain in touch with the latest happening in the java interview world.