Q/A & Example

Example & Q/A

1. What is difference between the jdk1.5 and jdk1.6 in java
1)Java 1.6 runs faster than Java 1.5.
2)Java 1.6 makes programming easier by implementing various tools such as SwingWorker and JTable to develop user interface.
3)Java 1.6 includes new or, in some cases, improved monitoring and management tools, including the "infamous" Jhat, which is used to explore core dumps. It also includes more diagnostic information, making bug fixing somewhat easier.
4)In java 1.6,Java DB, a new database management tool, has been included. Java DB is based on the open-source Apache Derby and is supported by Sun.

2. What is the Difference between DispatchAction and LookupDispatchAction ?
LookupDispatchAction is subclass of DispactAction class. The LookupDispatchAction class is used when you wants to add struts's internalization functionality in your application. Internalization means multiple languges supports application.If your using DispatchAction Class you will not be able to apply "internalization" functionality.
DispatchAction dispatches the action based on the parameter value. Where as lookupdispatchAction which is a subclass of it. It inherits all the properties but It supports one more additional method called getmethodkey() for all those mappings.

3. What is the difference between SessionState and ViewState?
The values of controls of a particular page of the client browser is persisted by ViewState at the time of post back operation is done. If the user requests another page, the data of previous page is no longer available.
The data of a particular server persists in the server by SessionState. The availability of the user data is up to the completion of a session or closure of the browser.

4. What is the difference between varchar & varchar2?
The difference between Varchar and Varchar2 is both are variable length but only 2000 bytes of character of data can be store in varchar where as 4000 bytes of character of data can be store in varchar2.
Varchar is used to store alphanumeric values without padding the unused memory locations whereas Varchar2 is also used to store alphanumeric values with padding the unused memory locations. So, by using varchar2 we are saving the memory locations.

5. What is the difference between JSP and Servlets ?
JSP is used mainly for presentation only. A JSP can only be HttpServlet that means the only supported protocol in JSP is HTTP. But a servlet can support any protocol like HTTP, FTP, SMTP etc.

6.What is a compilation unit? 
A compilation unit is a Java source code file.

7.What restrictions are placed on method overriding? 
Overridden methods must have the same name, argument list, and return type.
The overriding method may not limit the access of the method it overrides.
The overriding method may not throw any exceptions that may not be thrown by the overridden method.  


8.How can a dead thread be restarted?  
 A dead thread cannot be restarted.  


9.Which arithmetic operations can result in the throwing of an ArithmeticException?  
Integer / and % can result in the throwing of an ArithmeticException

10.What is numeric promotion? 
Numeric promotion is the conversion of a smaller numeric type to a larger numeric type, so that integer and floating-point operations may take place. In numerical promotion, byte, char, and short values are converted to int values. The int values are also converted to long values, if necessary. The long and float values are converted to double values, as required  .

11.What are synchronized methods and synchronized statements?  
Synchronized methods are methods that are used to control access to an object. A thread only executes a synchronized method after it has acquired the lock for the method's object or class. Synchronized statements are similar to synchronized methods. A synchronized statement can only be executed after a thread has acquired the lock for the object or class referenced in the synchronized statement.  

12.What is the diffrence between inner class and nested class?  
 When a class is defined within a scope od another class, then it becomes inner class.
If the access modifier of the inner class is static, then it becomes nested class.  

13.Diffrence between JRE And JVM AND JDK  
The "JDK" is the Java Development Kit. I.e., the JDK is bundle of software that you can use to develop Java based software. The "JRE" is the Java Runtime Environment. I.e., the JRE is an implementation of the Java Virtual Machine which actually executes Java programs. Typically, each JDK contains one (or more) JRE's along with the various development tools like the Java source compilers, bundling and deployment tools, debuggers, development libraries, etc.  

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

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

16.Why are there no global variables in Java?  
Global variables are considered bad form for a variety of reasons:
• Adding state variables breaks referential transparency (you no longer can understand a statement or expression on its own: you need to understand it in the context of the settings of the global variables).
• State variables lessen the cohesion of a program: you need to know more to understand how something works. A major point of Object-Oriented programming is to break up global state into more easily understood collections of local state.
• When you add one variable, you limit the use of your program to one instance. What you thought was global, someone else might think of as local: they may want to run two copies of your program at once.
For these reasons, Java decided to ban global variables.  

17.How to Retrieve Warnings?   (JDBC)
SQLWarning objects are a subclass of SQLException that deal with database access warnings. Warnings do not stop the execution of an application, as exceptions do; they simply alert the user that something did not happen as planned. A warning can be reported on a Connection object, a Statement object (including PreparedStatement and CallableStatement objects), or a ResultSet object. Each of these classes has a getWarnings method, which you must invoke in order to see the first warning reported on the calling object
E.g.
SQLWarning warning = stmt.getWarnings();
if (warning != null) {
while (warning != null) {
System.out.println("Message: " + warning.getMessage());
System.out.println("SQLState: " + warning.getSQLState());
System.out.print("Vendor error code: ");
System.out.println(warning.getErrorCode());
warning = warning.getNextWarning();
}
}  

18.Describe what happens when an object is created in Java?  
Several things happen in a particular order to ensure the object is constructed properly:
1. Memory is allocated from heap to hold all instance variables and implementation-specific data of the object and its superclasses. Implemenation-specific data includes pointers to class and method data.
2. The instance variables of the objects are initialized to their default values.
3. The constructor for the most derived class is invoked. The first thing a constructor does is call the consctructor for its superclasses. This process continues until the constrcutor for java.lang.Object is called, as java.lang.Object is the base class for all objects in java.
4. Before the body of the constructor is executed, all instance variable initializers and initialization blocks are executed. Then the body of the constructor is executed. Thus, the constructor for the base class completes first and constructor for the most derived class completes last.

19. Describe the visitor design pattern?
Represents an operation to be performed on the elements of an object structure. Visitor lets you define a new operation without changing the classes of the elements on which it operates. The root of a class hierarchy defines an abstract method to accept a visitor. Subclasses implement this method with visitor.visit(this). The Visitor interface has visit methods for all subclasses of the baseclass in the hierarchy.

20. What is a design pattern?  
A design pattern systematically names, motivates, and explains a general design that addresses a recurring design problem.  

21. 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.
<!--#include file="data.inc"-->
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 <!--#include file="data.inc"--> is used for including non-JSP files. 

22.Can a JSP page process HTML FORM data?  
Yes. However, unlike servlets, you are not required to implement HTTP-protocol specific methods like doGet() or doPost() within your JSP page. You can obtain the data for the FORM input elements via the request implicit object within a scriptlet or expression as:
<%
String item = request.getParameter("item");
int howMany = new Integer(request.getParameter("units")).intValue();
%>
or
<%= request.getParameter("item") %>


23. What JSP lifecycle methods can I override?  
Answer:   You cannot override the _jspService() method within a JSP page. You can however, override the jspInit() and jspDestroy() methods within a JSP page. jspInit() can be useful for allocating resources like database connections, network connections, and so forth for the JSP page. It is good programming practice to free any allocated resources within jspDestroy().
The jspInit() and jspDestroy() methods are each executed just once during the lifecycle of a JSP page and are typically declared as JSP declarations:
<%!
public void jspInit() {
. . .
}
%>

<%!
public void jspDestroy() {
. . .
}
%>

 24.How do I include static files within a JSP page?  
Static resources should always be included using the JSP include directive. This way, the inclusion is performed just once during the translation phase. The following example shows the syntax:
<%@ include file="copyright.html" %>
Do note that you should always supply a relative URL for the file attribute. Although you can also include static resources using the action, this is not advisable as the inclusion is then performed for each and every request. 

25.How do I perform browser redirection from a JSP page?  
You can use the response implicit object to redirect the browser to a different resource, as:
response.sendRedirect("http://www.foo.com/path/error.html");
You can also physically alter the Location HTTP header attribute, as shown below:
<%
response.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY);
String newLocn = "/newpath/index.html";
response.setHeader("Location",newLocn);
%>
You can also use the: <jsp:forward page="/newpage.jsp" /> Also note that you can only use this before any output has been sent to the client. I beleve this is the case with the response.sendRedirect() method as well.
If you want to pass any paramateres then you can pass using <jsp:forward page="/servlet/login"> <jsp:param name="username" value="jsmith" /> </jsp:forward>> 

26.Can a JSP page instantiate a serialized bean?  
No problem! The useBean action specifies the beanName attribute, which can be used for indicating a serialized bean. For example:
<jsp:useBean id="shop" type="shopping.CD" beanName="CD" /> <jsp:getProperty name="shop" property="album" />
A couple of important points to note. Although you would have to name your serialized file "filename.ser", you only indicate "filename" as the value for the beanName attribute. Also, you will have to place your serialized file within the WEB-INF\jsp\beans directory for it to be located by the JSP engine. 

27. Can you make use of a ServletOutputStream object from within a JSP page?  
No. You are supposed to make use of only a JSPWriter object (given to you in the form of the implicit object out) for replying to clients. A JSPWriter can be viewed as a buffered version of the stream object returned by response.getWriter(), although from an implementational perspective, it is not. A page author can always disable the default buffering for any page using a page directive as:
<%@ page buffer="none" %> 

28.What's a better approach for enabling thread-safe servlets and JSPs? SingleThreadModel Interface or Synchronization?  
Although the SingleThreadModel technique is easy to use, and works well for low volume sites, it does not scale well. If you anticipate your users to increase in the future, you may be better off implementing explicit synchronization for your shared data. The key however, is to effectively minimize the amount of code that is synchronzied so that you take maximum advantage of multithreading.
Also, note that SingleThreadModel is pretty resource intensive from the server's perspective. The most serious issue however is when the number of concurrent requests exhaust the servlet instance pool. In that case, all the unserviced requests are queued until something becomes free - which results in poor performance. Since the usage is non-deterministic, it may not help much even if you did add more memory and increased the size of the instance pool. 

29.Can I stop JSP execution while in the midst of processing a request?  
Yes. Preemptive termination of request processing on an error condition is a good way to maximize the throughput of a high-volume JSP engine. The trick (asuming Java is your scripting language) is to use the return statement when you want to terminate further processing. For example, consider:
<% if (request.getParameter("foo") != null) {
// generate some html or update bean property
} else {
/* output some error message or provide redirection back to the input form after creating a memento bean updated with the 'valid' form elements that were input. this bean can now be used by the previous form to initialize the input elements that were valid then, return from the body of the _jspService() method to terminate further processing */
return;
}
%> 

30.How can I get to view any compilation/parsing errors at the client while developing JSP pages?  
With JSWDK 1.0, set the following servlet initialization property within the \WEB-INF\servlets.properties file for your application:
jsp.initparams=sendErrToClient=true
This will cause any compilation/parsing errors to be sent as part of the response to the client. 

31.Is there a way to reference the "this" variable within a JSP page?  
Yes, there is. Under JSP 1.0, the page implicit object is equivalent to "this", and returns a reference to the servlet generated by the JSP page. 

32.How do I instantiate a bean whose constructor accepts parameters using the useBean tag?  
Consider the following bean: package bar;
public class FooBean {
public FooBean(SomeObj arg) {
...
}
//getters and setters here
}
The only way you can instantiate this bean within your JSP page is to use a scriptlet. For example, the following snippet creates the bean with session scope:
<% SomeObj x = new SomeObj(...);
bar.FooBean foobar = new FooBean(x);
session.putValue("foobar",foobar);
%> You can now access this bean within any other page that is part of the same session as: &l;%
bar.FooBean foobar = session.getValue("foobar");
%>
To give the bean "application scope", you will have to place it within the ServletContext as:
&l;%
application.setAttribute("foobar",foobar);
%>
To give the bean "request scope", you will have to place it within the request object as:
&l;%
request.setAttribute("foobar",foobar);
%>
If you do not place the bean within the request, session or application scope, the bean can be accessed only within the current JSP page (page scope).
Once the bean is instantiated, it can be accessed in the usual way:
jsp:getProperty name="foobar" property="someProperty"/ jsp:setProperty name="foobar" property="someProperty" value="someValue"/ 

Question:   Can I invoke a JSP error page from a servlet?  
Answer:   Yes, you can invoke the JSP error page and pass the exception object to it from within a servlet. The trick is to create a request dispatcher for the JSP error page, and pass the exception object as a javax.servlet.jsp.jspException request attribute. However, note that you can do this from only within controller servlets. If your servlet opens an OutputStream or PrintWriter, the JSP engine will throw the following translation error:
java.lang.IllegalStateException: Cannot forward as OutputStream or Writer has already been obtained
The following code snippet demonstrates the invocation of a JSP error page from within a controller servlet:
protected void sendErrorRedirect(HttpServletRequest request, HttpServletResponse response, String errorPageURL, Throwable e) throws ServletException, IOException {
request.setAttribute ("javax.servlet.jsp.jspException", e);
getServletConfig().getServletContext(). getRequestDispatcher(errorPageURL).forward(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response) {
try {
// do something
} catch (Exception ex) {
try {
sendErrorRedirect(request,response,"/jsp/MyErrorPage.jsp",ex);
} catch (Exception e) {
e.printStackTrace();
}
}

Question: Can we implement an interface in a JSP?  
Answer:   No 

Question: What is the difference between ServletContext and PageContext?  
Answer:   ServletContext: Gives the information about the container
PageContext: Gives the information about the Request 

Question: What is the difference in using request.getRequestDispatcher() and context.getRequestDispatcher()?  
Answer:   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. 

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

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

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

Question: How does JSP handle runtime exceptions?  
Answer:   Using errorPage attribute of page directive and also we need to specify isErrorPage=true if the current page is intended to URL redirecting of a JSP. 

Question: How do you delete a Cookie within a JSP?  
Answer:  
 Cookie mycook = new Cookie("name","value"); response.addCookie(mycook); Cookie killmycook = new Cookie("mycook","value"); killmycook.setMaxAge(0);
killmycook.setPath("/"); killmycook.addCookie(killmycook);

Question: How do I mix JSP and SSI #include?  
Answer:   If you're just including raw HTML, use the #include directive as usual inside your .jsp file.
<!--#include file="data.inc"-->
But it's a little trickier if you want the server to evaluate any JSP code that's inside the included file. Ronel Sumibcay (ronel@LIVESOFTWARE.COM) says: If your data.inc file contains jsp code you will have to use
<%@ vinclude="data.inc" %>
The <!--#include file="data.inc"--> is used for including non-JSP files. 

Question: How can you store international / Unicode characters into a cookie?  
Answer:   One way is, before storing the cookie URLEncode it.
URLEnocder.encoder(str);
And use URLDecoder.decode(str) when you get the stored cookie.

Question: What are the implicit objects?  
Answer:   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

 Question: Is JSP technology extensible?  
Answer:   YES. JSP technology is extensible through the development of custom actions, or tags, which are encapsulated in tag libraries 

 Question: How can I implement a thread-safe JSP page? What are the advantages and Disadvantages of using it?  
Answer:   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 

Question: How does JSP handle run-time exceptions?  
Answer:   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" %>
the 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. 

Question: How do I prevent the output of my JSP or Servlet pages from being cached by the browser?  
Answer:   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
%>


Question: How do I use comments within a JSP page?  
Answer:   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 javagalaxy.com -->
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
**/
%>

 Question: Response has already been commited error. What does it mean?  
Answer:   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...) ... and 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 

Question: How do I use a scriptlet to initialize a newly instantiated bean?  
Answer:   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" class="com.Bar.Foo" >
<jsp:setProperty name="foo" property="today" value="<%=java.text.DateFormat.getDateInstance().format(new java.util.Date()) %>"/ >
<%-- scriptlets calling bean setter methods go here --%>
</jsp:useBean > 

Question: How can I enable session tracking for JSP pages if the browser has disabled cookies?  
Answer:   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");
%>
<a href='<%=url%>'>hello2.jsp</a>
hello2.jsp
<%@ page session="true" %>
<%
Integer i= (Integer )session.getValue("num");
out.println("Num value in session is "+i.intValue());

 Question: How can I declare methods within my JSP page?  
Answer:   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"%>
<html>
<body>
<%test(out);% >
</body>
</html> 

Question: Is there a way I can set the inactivity lease period on a per-session basis?  
Answer:   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. 

Question: How can I set a cookie and delete a cookie from within a JSP page?  
Answer:   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);
%> 

Question: How does a servlet communicate with a JSP page?  
Answer:   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" / 

Question: How do I have the JSP-generated servlet subclass my own custom servlet class, instead of the default?   
Answer:   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" %< 

Question: 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?  
Answer:   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)% >" > 

Question: How can I get to print the stacktrace for an exception occuring within my JSP page?  
Answer:   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("
");
%> 

Question: How do you pass an InitParameter to a JSP?  
Answer:   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);
}
}
%> 

Question: How can my JSP page communicate with an EJB Session Bean?  
Answer:   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...
%> 

Question: How can my application get to know when a HttpSession is removed?  
Answer:   Define a Class HttpSessionNotifier which implements HttpSessionBindingListener and implement the functionality what you need in valueUnbound() method.
Create an instance of that class and put that instance in HttpSession. 

Question: How do I include static files within a JSP page?  
Answer:   Static resources should always be included using the JSP include directive. This way, the inclusion is performed just once during the translation phase. The following example shows the syntax: Do note that you should always supply a relative URL for the file attribute. Although you can also include static resources using the action, this is not advisable as the inclusion is then performed for each and every request. 

Question: What is a output comment?
Answer: A comment that is sent to the client in the viewable page source.The JSP engine handles an output comment as uninterpreted HTML text, returning the comment in the HTML output sent to the client. You can see the comment by viewing the page source from your Web browser.
JSP Syntax
<!-- comment [ <%= expression %> ] -->
Example 1
<!-- This is a commnet sent to client on
<%= (new java.util.Date()).toLocaleString() %>
-->
Displays in the page source:
<!-- This is a commnet sent to client on January 24, 2004 -->

Question: What is a Hidden Comment?
Answer: A comments that documents the JSP page but is not sent to the client. The JSP engine ignores a hidden comment, and does not process any code within hidden comment tags. A hidden comment is not sent to the client, either in the displayed JSP page or the HTML page source. The hidden comment is useful when you want to hide or "comment out" part of your JSP page.
You can use any characters in the body of the comment except the closing --%> combination. If you need to use --%> in your comment, you can escape it by typing --%\>.
JSP Syntax
<%-- comment --%>
Examples
<%@ page language="java" %>
<html>
<head><title>A Hidden Comment </title></head>
<body>
<%-- This comment will not be visible to the colent in the page source --%>
</body>
</html>
Question: What is a Expression?
Answer: An expression tag contains a scripting language expression that is evaluated, converted to a String, and inserted where the expression appears in the JSP file. Because the value of an expression is converted to a String, you can use an expression within text in a JSP file. Like
<%= someexpression %>
<%= (new java.util.Date()).toLocaleString() %>
You cannot use a semicolon to end an expression

Question: What is a Declaration?
Answer: A declaration declares one or more variables or methods for use later in the JSP source file.
A declaration must contain at least one complete declarative statement. You can declare any number of variables or methods within one declaration tag, as long as they are separated by semicolons. The declaration must be valid in the scripting language used in the JSP file.
<%! somedeclarations %>
<%! int i = 0; %>
<%! int a, b, c; %>

Question: What is a Scriptlet?
Answer: A scriptlet can contain any number of language statements, variable or method declarations, or expressions that are valid in the page scripting language.Within scriptlet tags, you can
1.Declare variables or methods to use later in the file (see also Declaration).
2.Write expressions valid in the page scripting language (see also Expression).
3.Use any of the JSP implicit objects or any object declared with a <jsp:useBean> tag.
You must write plain text, HTML-encoded text, or other JSP tags outside the scriptlet.
Scriptlets are executed at request time, when the JSP engine processes the client request. If the scriptlet produces output, the output is stored in the out object, from which you can display it.

Question: What are implicit objects? List them?
Answer: Certain objects that are available for the use in JSP documents without being declared first. These objects are parsed by the JSP engine and inserted into the generated servlet. The implicit objects re listed below
request
response
pageContext
session
application
out
config
page
exception

Question: Difference between forward and sendRedirect?
Answer: When you invoke a forward request, the request is sent to another resource on the server, without the client being informed that a different resource is going to process the request. This process occurs completly with in the web container.  When a sendRedirtect method is invoked, it causes the web container to return to the browser indicating that a new URL should be requested. Because the browser issues a completly new request any object that are stored as request attributes before the redirect occurs will be lost. This extra round trip a redirect is slower than forward.
Question: What are the different scope valiues for the <jsp:useBean>?
Answer: The different scope values for <jsp:useBean> are
1. page
2. request
3.session
4.application

Question: Explain the life-cycle mehtods in JSP?
Answer: THe generated servlet class for a JSP page implements the HttpJspPage interface of the javax.servlet.jsp package. Hte HttpJspPage interface extends the JspPage interface which inturn extends the Servlet interface of the javax.servlet package. the generated servlet class thus implements all the methods of the these three interfaces. The JspPage interface declares only two mehtods - jspInit() and jspDestroy() that must be implemented by all JSP pages regardless of the client-server protocol. However the JSP specification has provided the HttpJspPage interfaec specifically for the JSp pages serving HTTP requests. This interface declares one method _jspService().
The jspInit()- The container calls the jspInit() to initialize te servlet instance.It is called before any other method, and is called only once for a servlet instance.
The _jspservice()- The container calls the _jspservice() for each request, passing it the request and the response objects.
The jspDestroy()- The container calls this when it decides take the instance out of service. It is the last method called n the servlet instance.

  
SERVLET

Question: What are the phases in JSP?   
Answer:   a) Translation phase ? conversion of JSP to a Servlet source, and then Compilation of servlet source into a class file. The translation phase is typically carried out by the JSP engine itself, when it receives an incoming request for the JSP page for the first time
b) init(), service() and destroy() method as usual as Servlets. 

Question: How many cookies can one set in the response object of the servlet? Also, are there any restrictions on the size of cookies?   
Answer:   If the client is using Netscape, the browser can receive and store 300 total cookies
4 kilobytes per cookie (including name)
20 cookies per server or domain

Question: What?s the difference between sendRedirect( ) and forward( ) methods?   
Answer:   A sendRedirect method creates a new request (it?s also reflected in browser?s URL ) where as forward method forwards the same request to the new target(hence the chnge is NOT reflected in browser?s URL).
The previous request scope objects are no longer available after a redirect because it results in a new request, but it?s available in forward.
SendRedirectis slower compared to forward. 

Question: Is there some sort of event that happens when a session object gets bound or unbound to the session?    
Answer:   HttpSessionBindingListener will hear the events When an object is added and/or remove from the session object, or when the session is invalidated, in which case the objects are first removed from the session, whether the session is invalidated manually or automatically (timeout). 

Question: What do the differing levels of bean storage (page, session, app) mean?   
Answer:   page life time - NO storage. This is the same as declaring the variable in a scriptlet and using it from there.
session life time - request.getSession(true).putValue "myKey", myObj);
application level ? getServletConfig().getServletContext().setAttribute("myKey ",myObj )
request level - The storage exists for the lifetime of the request, which may be forwarded between jsp's and servlets 

Question: Is it true that servlet containers service each request by creating a new thread? If that is true, how does a container handle a sudden dramatic surge in incoming requests without significant performance degradation?   
Answer:   The implementation depends on the Servlet engine. For each request generally, a new Thread is created. But to give performance boost, most containers, create and maintain a thread pool at the server startup time. To service a request, they simply borrow a thread from the pool and when they are done, return it to the pool. 
For this thread pool, upper bound and lower bound is maintained. Upper bound prevents the resource exhaustion problem associated with unlimited thread allocation. The lower bound can instruct the pool not to keep too many idle threads, freeing them if needed. 

Question: Can I just abort processing a JSP?   
Answer:   Yes. Because your JSP is just a servlet method, you can just put (whereever necessary) a < % return; % > 

Question: What is URL Encoding and URL Decoding ?   
Answer:   URL encoding is the method of replacing all the spaces and other extra characters into their corresponding Hex Characters and Decoding is the reverse process converting all Hex Characters back their normal form.
For Example consider this URL, /ServletsDirectory/Hello'servlet/
When Encoded using URLEncoder.encode("/ServletsDirectory/Hello'servlet/") the output is
http%3A%2F%2Fwww.javacommerce.com%2FServlets+Directory%2FHello%27servlet%2FThis can be decoded back using
URLDecoder.decode("http%3A%2F%2Fwww.javacommerce.com%2FServlets+Directory%2FHello%27servlet%2F") 

Question: Do objects stored in a HTTP Session need to be serializable? Or can it store any object?   
Answer:   Yes, the objects need to be serializable, but only if your servlet container supports persistent sessions. Most lightweight servlet engines (like Tomcat) do not support this. However, many EJB-enabled servlet engines do. Even if your engine does support persistent sessions, it is usually possible to disable this feature. 

Question: What is the difference between session and cookie?   
Answer:   The difference between session and a cookie is two-fold.
1) session should work regardless of the settings on the client browser. even if users decide to forbid the cookie (through browser settings) session still works. there is no way to disable sessions from the client browser.
2) session and cookies differ in type and amount of information they are capable of storing.
Javax.servlet.http.Cookie class has a setValue() method that accepts Strings. javax.servlet.http.HttpSession has a setAttribute() method which takes a String to denote the name and java.lang.Object which means that HttpSession is capable of storing any java object. Cookie can only store String objects. 

Question: What is the difference between ServletContext and ServletConfig?   
Answer:   Both are interfaces.
The servlet engine implements the ServletConfig interface in order to pass configuration information to a servlet. The server passes an object that implements the ServletConfig interface to the servlet's init() method.
The ServletContext interface provides information to servlets regarding the environment in which they are running. It also provides standard way for servlets to write events to a log file. 

Question: What are the differences between GET and POST service methods?   
Answer:   A GET request is a request to get a resource from the server. Choosing GET as the "method" will append all of the data to the URL and it will show up in the URL bar of your browser. The amount of information you can send back using a GET is restricted as URLs can only be 1024 characters. A POST request is a request to post (to send) form data to a resource on the server. A POST on the other hand will (typically) send the information through a socket back to the webserver and it won't show up in the URL bar. You can send much more information to the server this way - and it's not restricted to textual data either. It is possible to send files and even binary data such as serialized Java objects! 

Question: What is the difference between GenericServlet and HttpServlet?   
Answer:   GenericServlet is for servlets that might not use HTTP, like for instance FTP service.As of only Http is implemented completely in HttpServlet.
The GenericServlet has a service() method that gets called when a client request is made. This means that it gets called by both incoming requests and the HTTP requests are given to the servlet as they are 

Question: What is HttpTunneling?   
Answer:   HTTP tunneling is used to encapsulate other protocols within the HTTP or HTTPS protocols. Normally the intra-network of an organization is blocked by a firewall and the network is exposed to the outer world only through a specific web server port , that listens for only HTTP requests. To use any other protocol, that by passes the firewall, the protocol is embedded in HTTP and send as HttpRequest. 

Question: What is Server Side Push and how is it implemented and when is it useful?   
Answer:   Server Side push is useful when data needs to change regularly on the clients application or browser, without intervention from client. Standard examples might include apps like Stock's Tracker, Current News etc. As such server cannot connect to client's application automatically. The mechanism used is, when client first connects to Server, (Either through login etc..), then Server keeps the TCP/IP connection open.
It's not always possible or feasible to keep the connection to Server open. So another method used is, to use the standard HTTP protocols ways of refreshing the page, which is normally supported by all browsers.
<META HTTP-EQUIV="Refresh" CONTENT="5;URL=/servlet/stockquotes/">
This will refresh the page in the browser automatically and loads the new data every 5 seconds. 

Question: Request parameter How to find whether a parameter exists in the request object?   
Answer:   1.boolean hasFoo = !(request.getParameter("foo") == null || request.getParameter("foo").equals(""));
2. boolean hasParameter = request.getParameterMap().contains(theParameter);
(which works in Servlet 2.3+) 

Question: How can I send user authentication information while makingURLConnection?   
Answer:   You'll want to use HttpURLConnection.setRequestProperty and set all the appropriate headers to HTTP authorization. 

Question: What is the Max amount of information that can be saved in a Session Object ?   
Answer:   As such there is no limit on the amount of information that can be saved in a Session Object. Only the RAM available on the server machine is the limitation. The only limit is the Session ID length(Identifier) , which should not exceed more than 4K. If the data to be store is very huge, then it's preferred to save it to a temporary file onto hard disk, rather than saving it in session. Internally if the amount of data being saved in Session exceeds the predefined limit, most of the servers write it to a temporary cache on Hard disk. 

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

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

Question: The code in a finally clause will never fail to execute, right?   
Answer:   Using System.exit(1); in try block will not allow finally code to execute.  

************************************Examples********************************************************************************

1.     Program to reverse a given number using while loop 
1.     
COMMAND LINE ARGUMENT: */
/* num - INPUT NUMBER TO BE REVERSED */
/* ---------------------------------------------------------------- */

public class Reverse
{
public static void main(String [] args)
{
int num = Integer.parseInt(args[0]);
int num1,t;
long rev = 0;
num1 = num;
while(num1 != 0)
{
t = num1 % 10;
rev = rev * 10 + t;
num1 /= 10;
}
System.out.print("The Reverse Of " + num + " Is " + rev);
}
}


***********************************************************************************************************************************

2.     Program to raise a number to the given power
COMMAND LINE ARGUMENTS : */
/* n1 - BASE NUMBER */
/* n2 - POWER NUMBER */
/* ---------------------------------------------------------------- */

public class Power
{
static double p = 1.0;
public static void main(String [] args)
{
double n1 = Double.parseDouble(args[0]);
double n2 = Double.parseDouble(args[1]);
double lpower = Math.pow(n1,n2);
double upower = power(n1,n2);
System.out.println("\nUsing Math Class\'s pow Method : ");
System.out.println(n1 + " ^ " + n2 + " = " + lpower);
System.out.println("\nUsing User-Defined Method : ");
System.out.println(n1 + " ^ " + n2 + " = " + upower);
}
private static double power(double n1, double n2)
{
if(n2 >= 0)
while(n2-- > 0)
p *= n1;
else
while(n2++ < 0)
p /= n1;
return p;
}
}

***********************************************************************************************************************************


3.     Public Class OddEven
{
public static void main(String args[]) throws IOException
{
DataInputStream din = new DataInputStream(System.in);
int ar[] = new int[10];
int n,i;
System.out.print("Enter The Array Length : ");
n = Integer.parseInt(din.readLine());
System.out.println("\nEnter " + n + " Elements for the array : ");
for(i = 0;i < n;i++)
ar[i] = Integer.parseInt(din.readLine());
int o = 0,e = 0;
for(i = 0;i <n;i++)
{
if (ar[i] % 2 == 0)
e++;
else
o++;
}
System.out.println("The Number Of Odd Elements Are : " + o);
System.out.println(" The Number Of Even Elements Are : " + e);
}
}

***********************************************************************************************************************************


4.     Program to find whether the given number is prime or not
COMMAND LINE ARGUMENT : */
/* n - INPUT NUMBER */
/* ---------------------------------------------------------------- */

public class Prime
{
public static void main(String [] args)
{
int n = Integer.parseInt(args[0]);
if(n <= 1)
System.out.println("Enter A +ve Number > 1");
else
{
int d,fin,divided;
if((n == 2) || (n == 3))
System.out.println("\n" + n + " Is Prime");
else
if(n % 2 == 0)
System.out.println("\n" + n + " Is Not Prime");
else
{
fin = (int)(Math.sqrt(n));
d = 3;
divided = 0; // Not Yet Divided
do
{
if(n % d == 0)
divided = 1;
else
d += 2;
}while((divided != 1) && (d <= fin));
if(divided == 1)
System.out.println("\n" + n + " Is Not Prime");
else
System.out.println("\n" + n + " Is Prime");
}
}
}
}


***********************************************************************************************************************************

5.     Program to reverse a given number using while loop
COMMAND LINE ARGUMENT : */
/* rs - VALUE IN RUPEES */
/* ---------------------------------------------------------------- */

public class Price
{
public static void main(String [] args)
{
float rs = Float.parseFloat(args[0]);
int ps = (int)(rs * 100);
System.out.println("Rs. " + rs + " = " + ps + " paise");
}
}


***********************************************************************************************************************************

6.     Reader Demo1
Public Class Reader Demo1
{
public static void main(String [] args) throws IOException, Exception
{
InputStreamReader inr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(inr);
int i = 0; float f = 0; boolean bo = false;
System.out.println("Enter An Int : ");
i = Integer.parseInt(br.readLine());
System.out.println("Enter A Float : ");
f = Float.valueOf(br.readLine()).floatValue();
System.out.println("Enter A boolean Value : ");
bo = Boolean.valueOf(br.readLine()).booleanValue();
Clear.screen();
System.out.println("Entered Int = " + i);
System.out.println("Entered Float = " + f);
System.out.println("Entered Boolean = " + bo);
}              
}


***********************************************************************************************************************************

7.     Power of a Number
COMMAND LINE ARGUMENTS : */
/* n1 - BASE NUMBER */
/* n2 - POWER NUMBER */
/* ---------------------------------------------------------------- */

public class Power
{
static double p = 1.0;
public static void main(String [] args)
{
double n1 = Double.parseDouble(args[0]);
double n2 = Double.parseDouble(args[1]);
double lpower = Math.pow(n1,n2);
double upower = power(n1,n2);
System.out.println("\nUsing Math Class\'s pow Method : ");
System.out.println(n1 + " ^ " + n2 + " = " + lpower);
System.out.println("\nUsing User-Defined Method : ");
System.out.println(n1 + " ^ " + n2 + " = " + upower);
}
private static double power(double n1, double n2)
{
if(n2 >= 0)
while(n2-- > 0)
p *= n1;
else
while(n2++ < 0)
p /= n1;
return p;
}
}

***********************************************************************************************************************************

8.     Leap Year

Public Class Leap Year
{
public static void main(String args[]) throws IOException
{
int yea;
DataInputStream din = new DataInputStream(System.in);
System.out.println("Enter A Year : ");
yea = Integer.parseInt(din.readLine());
boolean isLeap = leap(yea);
if (isLeap == true)
System.out.println(yea + " Is A Leap Year");
else
System.out.println(yea + " Is Not A Leap Year");
}
private static boolean leap(int y)
{
if((y % 4 == 0) && (y % 100 != 0) || (y % 400 == 0))
return true;
else
return false;
}
}


***********************************************************************************************************************************


9.     List a File
Public Class List File

{
public static void main(String arg[])
{
File f=new File(arg[0]);
if(f.exists()&&f.isDirectory())
{
String fname[]=f.list();
for(int i=0;i<fname.length;i++)
{
File ff=new File(f.getPath(),fname[i]);
if(ff.isDirectory())
System.out.println(fname[i]+"\t\t\t==<dir>");
else
System.out.println(fname[i]);
}
}
else
System.out.println("file is not a directory or nor exists");
}
}

Program to demonstrate matrix input and output

import java.io.*;
public class Matrix
{
public static void main(String [] args) throws IOException, Exception
{
byte mat[][] = new byte[10][10];
int i,j,m,n;
DataInputStream din = new DataInputStream(System.in);
System.out.println("Enter The Order Of Matrix : ");
m = Integer.parseInt(din.readLine());
n = Integer.parseInt(din.readLine());
System.out.println("Enter The Elements One By One : ");
for (i = 0;i < m;i++)
for(j = 0;j < n;j++)
mat[i][j] = Byte.parseByte(din.readLine());
System.out.println("The Matrix elements Are : \n");
for(i = 0;i < m;i++)
{
for(j = 0;j < n;j++)
System.out.print(" " + mat[i][j]);
System.out.println("");
}

}
}


***********************************************************************************************************************************

10.   Program to search files similar to dir/s in dos

import java.io.*;
import clrscr.*;
public class FileSearch
{
public static void main(String arg[])
{
Clear.screen();
File f=new File(arg[0]);
if(f.exists())
if(f.isDirectory())
{
File fname = new File(f.getName());
listFiles(fname);
}
else
System.out.println(f.getName());
else
System.out.println("file is not a directory or nor exists");
}

private static void listFiles(File f)
{
String filename[] = f.list();
for(int i=0;i<filename.length-1;i++)
{
File ff=new File(f.getPath(),filename[i]);
if(ff.isDirectory())
{
System.out.println("Listing OF Directory : " + filename[i] + "\n");
String fname1[] = ff.list();
for(int j=0;j<fname1.length-1;j++)
{
File ff1=new File(f.getPath(),fname1[j]);
if(ff1.isDirectory())
{
File fn = new File(ff1.getName());
listFiles(fn);
}
else
System.out.println(fname1[j]);
}
}
}
}
}

***********************************************************************************************************************************

Q: What is a Thread?
Ans) In Java, “thread” means two different things: An instance of class java.lang.Thread. A thread of execution.
An instance of Thread is just…an object. Like any other object in Java, it has variables and methods, and lives and dies on the heap. But a thread of execution is an individual process (a “lightweight” process) that has its own call stack. In Java, there is one thread per call stack—or, to think of it in reverse, one call stack per thread. Even if you don’t create any new threads in your program, threads are back there running.
The main() method, that starts the whole ball rolling, runs in one thread, called (surprisingly) the main thread. If you looked at the main call stack (and you can, any time you get a stack trace from something that happens after main begins, but not within another thread), you’d see that main() is the first method on the stack— the method at the bottom. But as soon as you create a new thread, a new stack materializes and methods called from that thread run in a call stack that’s separate from the main() call stack.

Q: What is difference between thread and process?
Ans) Differences between threads and processes are:-
1. Threads share the address space of the process that created it; processes have their own address.
2. Threads have direct access to the data segment of its process; processes have their own copy of the data segment of the parent process.
3. Threads can directly communicate with other threads of its process; processes must use interprocess communication to communicate with sibling processes.
4. Threads have almost no overhead; processes have considerable overhead.
5. New threads are easily created; new processes require duplication of the parent process.
6. Threads can exercise considerable control over threads of the same process; processes can only exercise control over child processes.
7. Changes to the main thread (cancellation, priority change, etc.) may affect the behavior of the other threads of the process; changes to the parent process do not affect child processes.

Q: What are the advantages or usage of threads?
Ans)Threads support concurrent operations. For example,
• Multiple requests by a client on a server can be handled as an individual client thread.

• Long computations or high-latency disk and network operations can be handled in the background without disturbing foreground computations or screen updates.
Threads often result in simpler programs.

• In sequential programming, updating multiple displays normally requires a big while-loop that performs small parts of each display update. Unfortunately, this loop basically simulates an operating system scheduler. In Java, each view can be assigned a thread to provide continuous updates.

• Programs that need to respond to user-initiated events can set up service routines to handle the events without having to insert code in the main routine to look for these events.
Threads provide a high degree of control.
• Imagine launching a complex computation that occasionally takes longer than is satisfactory. A “watchdog” thread can be activated that will “kill” the computation if it becomes costly, perhaps in favor of an alternate, approximate solution. Note that sequential programs must muddy the computation with termination code, whereas, a Java program can use thread control to non-intrusively supervise any operation.
Threaded applications exploit parallelism.

• A computer with multiple CPUs can literally execute multiple threads on different functional units without having to simulating multi-tasking (“time sharing”).

• On some computers, one CPU handles the display while another handles computations or database accesses, thus, providing extremely fast user interface response times.


Q:  What are the two ways of creating thread?
Ans) There are two ways to create a new thread.
1)Extend the Thread class and override the run() method in your class. Create an instance of the subclass and invoke the start() method on it, which will create a new thread of execution. e.g.
public class NewThread extends Thread{
public void run(){
// the code that has to be executed in a separate new thread goes here
}
public static void main(String [] args){
NewThread c = new NewThread();
c.start();
}
}

2)Implements the Runnable interface.The class will have to implement the run() method in the Runnable interface. Create an instance of this class. Pass the reference of this instance to the Thread constructor a new thread of execution will be created. e.g. class
public class NewThread implements Runnable{
public void run(){
// the code that has to be executed in a separate new thread goes here
}
public static void main(String [] args){
NewThread c = new NewThread();
Thread t = new Thread(c);
t.start();
}
}

Q: What are the different states of a thread’s lifecycle?
Ans) The different states of threads are as follows:
1) New – When a thread is instantiated it is in New state until the start() method is called on the thread instance. In this state the thread is not considered to be alive.
2) Runnable – The thread enters into this state after the start method is called in the thread instance. The thread may enter into the Runnable state from Running state. In this state the thread is considered to be alive.
3) Running – When the thread scheduler picks up the thread from the Runnable thread’s pool, the thread starts running and the thread is said to be in Running state.
4) Waiting/Blocked/Sleeping – In these states the thread is said to be alive but not runnable. The thread switches to this state because of reasons like wait method called or sleep method has been called on the running thread or thread might be waiting for some i/o resource so blocked. 5) Dead – When the thread finishes its execution i.e. the run() method execution completes, it is said to be in dead state. A dead state can not be started again. If a start() method is invoked on a dead thread a runtime exception will occur.

Q: What is use of synchronized keyword?
Ans) synchronized keyword can be applied to static/non-static methods or a block of code. Only one thread at a time can access synchronized methods and if there are multiple threads trying to access the same method then other threads have to wait for the execution of method by one thread. Synchronized keyword provides a lock on the object and thus prevents race condition. E.g.
public void synchronized method(){}
public void synchronized staticmethod(){}
public void myMethod(){
synchronized (this){ // synchronized keyword on block of code
}
}

Q: What is the difference when the synchronized keyword is applied to a static method or to a non static method?
Ans) When a synch non static method is called a lock is obtained on the object. When a synch static method is called a lock is obtained on the class and not on the object. The lock on the object and the lock on the class don’t interfere with each other. It means, a thread accessing a synch non static method, then the other thread can access the synch static method at the same time but can’t access the synch non static method.

Q: What is a volatile keyword?
Ans) In general each thread has its own copy of variable, such that one thread is not concerned with the value of same variable in the other thread. But sometime this may not be the case. Consider a scenario in which the count variable is holding the number of times a method is called for a given class irrespective of any thread calling, in this case irrespective of thread access the count has to be increased so the count variable is declared as volatile. The copy of volatile variable is stored in the main memory, so every time a thread access the variable even for reading purpose the local copy is updated each time from the main memory. The volatile variable also have performance issues.

Q: What is the difference between yield() and sleep()?
Ans) yield() allows the current the thread to release its lock from the object and scheduler gives the lock of the object to the other thread with same priority.
sleep() allows the thread to go to sleep state for x milliseconds. When a thread goes into sleep state it doesn’t release the lock.

Q: What is the difference between wait() and sleep()?
Ans)
1) wait() is a method of Object class. sleep() is a method of Object class.
2) sleep() allows the thread to go to sleep state for x milliseconds. When a thread goes into sleep state it doesn’t release the lock. wait() allows thread to release the lock and goes to suspended state. The thread is only active when a notify() or notifAll() method is called for the same object.

Q: What is difference between notify() and notfiyAll()?
Ans) notify( ) wakes up the first thread that called wait( ) on the same object.
notifyAll( ) wakes up all the threads that called wait( ) on the same object. The
highest priority thread will run first.

Q: What happens if a start method is not invoked and the run method is directly invoked?
Ans) If a thread has been instantiated but not started its is said to be in new state. Unless until a start() method is invoked on the instance of the thread, it will not said to be alive. If you do not call a start() method on the newly created thread instance thread is not considered to be alive. If the start() method is not invoked and the run() method is directly called on the Thread instance, the code inside the run() method will not run in a separate new thread but it will start running in the existing thread.

Q: What happens when start() is called?
Ans) A new thread of execution with a new call stack starts. The state of thread changes from new to runnable. When the thread gets chance to execute its target run() method starts to run.

Q: If code running is a thread creates a new thread what will be the initial priority of the newly created thread?
Ans) When a code running in a thread creates a new thread object , the priority of the new thread is set equal to the priority of the thread which has created it.

Q: When jvm starts up, which thread will be started up first?
Ans) When jvm starts up the thread executing main method is started.

Q: What are the daemon threads?
Ans) Daemon thread are service provider threads run in the background,these not used to run the application code generally.When all user threads(non-daemon threads) complete their execution the jvm exit the application whatever may be the state of the daemon threads. Jvm does not wait for the daemon threads to complete their execution if all user threads have completed their execution.

To create Daemon thread set the daemon value of Thread using setDaemon(boolean value) method. By default all the threads created by user are user thread. To check whether a thread is a Daemon thread or a user thread use isDaemon() method.

Example of the Daemon thread is the Garbage Collector run by jvm to reclaim the unused memory by the application. The Garbage collector code runs in a Daemon thread which terminates as all the user threads are done with their execution.

Q: What all constructors are present in the Thread class?
Ans) Thread()
Thread(Runnable target)
Thread(Runnable target, String name)
Thread(String name)

Q: Can the variables or classes be Synchronized?
Ans) No. Only methods can be synchronized.

Q: How many locks does an object have?
Ans) Each object has only one lock.

Q: Can a class have both Synchronized and non-synchronized methods?
Ans) Yes a class can have both synchronized and non-synchronized methods.

Q: If a class has a synchronised method and non-synchronised method, can multiple threads execute the non-synchronised methods?
Ans) Yes. If a class has a synchronised and non-synchronised methods, multiple threads can access the non-synchronised methods.

Q: If a thread goes to sleep does it hold the lock?
Ans) Yes when a thread goes to sleep it does not release the lock.

Q: Can a thread hold multiple locks at the same time?
Ans) Yes. A thread can hold multiple locks at the same time. Once a thread acquires a lock and enters into the synchronized method / block, it may call another synchronized method and acquire a lock on another object.

Q: Can a thread call multiple synchronized methods on the object of which it hold the lock?
Ans) Yes. Once a thread acquires a lock in some object, it may call any other synchronized method of that same object using the lock that it already holds.

Q : Can static methods be synchronized?
Ans) Yes. As static methods are class methods and have only one copy of static data for the class, only one lock for the entire class is required. Every class in java is represented by java.lang.Class instance. The lock on this instance is used to synchronize the static methods.

Q: Can two threads call two different static synchronized methods of the same class?
Ans) No. The static synchronized methods of the same class always block each other as only one lock per class exists. So no two static synchronized methods can execute at the same time.

Q : Does a static synchronized method block a non-static synchronized method?
Ans)No As the thread executing the static synchronized method holds a lock on the class and the thread executing the non-satic synchronized method holds the lock on the object on which the method has been called, these two locks are different and these threads do not block each other.

Q: Once a thread has been started can it be started again?
Ans) No. Only a thread can be started only once in its lifetime. If you try starting a thread which has been already started once an IllegalThreadStateException is thrown, which is a runtime exception. A thread in runnable state or a dead thread can not be restarted.

Q: When does deadlock occur and how to avoid it?
Ans) When a locked object tries to access a locked object which is trying to access the first locked object. When the threads are waiting for each other to release the lock on a particular object, deadlock occurs .

Q: What is a better way of creating multithreaded application? Extending Thread class or implementing Runnable?
Ans) If a class is made to extend the thread class to have a multithreaded application then this subclass of Thread can not extend any other class and the required application will have to be added to this class as it can not be inherited from any other class. If a class is made to implement Runnable interface, then the class can extend other class or implement other interface.

Q: Can the start() method of the Thread class be overridden? If yes should it be overridden?
Ans) Yes the start() method can be overridden. But it should not be overridden as it’s implementation in thread class has the code to create a new executable thread and is specialised.

Q: What are the methods of the thread class used to schedule the threads?
Ans) The methods are as follows:
public static void sleep(long millis) throws InterruptedException
public static void yield()
public final void join() throws InterruptedException
public final void setPriority(int priority)
public final void wait() throws InterruptedException
public final void notify()
public final void notifyAll()

Q: Which thread related methods are available in Object class?
Ans) The methods are:
public final void wait() throws Interrupted exception
public final void notify()
public final void notifyAll()

Q: Which thread related methods are available in Thread class?
Ans) Methods which are mainly used :
public static void sleep(long millis) throws Interrupted exception
public static void yield() public final void join() throws Interrupted exception
public final void setPriority(int priority)
public void start()
public void interrupt()
public final void join()
public void run()
public void resume()

Q: List the methods which when called the thread does not release the locks held?
Ans) Following are the methods.
notify()
join()
sleep()
yield()

Q: List the methods which when called on the object the thread releases the locks held on that object?
Ans) wait()

Q: Does each thread has its own thread stack?
Ans) Yes each thread has its own call stack. For eg
Thread t1 = new Thread();
Thread t2 = new Thread();
Thread t3 = t1;
In the above example t1 and t3 will have the same stack and t2 will have its own independent stack.

Q: What is thread starvation?
Ans) In a multi-threaded environment thread starvation occurs if a low priority thread is not able to run or get a lock on the resoruce because of presence of many high priority threads. This is mainly possible by setting thread priorities inappropriately.

Q: What is threadLocal variable?
Ans) ThreadLocal is a class. If a variable is declared as threadLocal then each thread will have a its own copy of variable and would not interfere with the other’s thread copy. Typical scenario to use this would be giving JDBc connection to each thread so that there is no conflict.
ThreadLocal class by JAVA API
public class ThreadLocal {
public Object get();
public void set(Object newValue);
public Object initialValue();
}
Implementation of ThreadLocal
public class ConnectionDispenser {
private static class ThreadLocalConnection extends ThreadLocal {
public Object initialValue() {
return DriverManager.getConnection(ConfigurationSingleton.getDbUrl());
}
}
private static ThreadLocalConnection conn = new ThreadLocalConnection();
public static Connection getConnection() {
return (Connection) conn.get();
}
}

Q: What’s the difference between Thread and Runnable types?
A: A Java Thread controls the main path of execution in an application. When you invoke the Java Virtual Machine with the java command, it creates an implicit thread in which to execute the main method. The Thread class provides a mechanism for the first thread to start-up other threads to run in parallel with it.
The Runnable interface defines a type of class that can be run by a thread. The only method it requires is run, which makes the interface very easy to fulfil by extending existing classes. A runnable class may have custom constructors and any number of other methods for configuration and manipulation.

Q: How does the run() method in Runnable work?
A: It may help to think of the run method like the main method in standard single threaded applications. The run method is a standard entry point to run or execute a class. The run method is normally only executed in the context of an independent Thread, but is a normal method in all other respects.

Q: Why not override Thread to make a Runnable?
A: There is little difference in the work required to override the Thread class compared with implementing the Runnable interface, both require the body of the run() method. However, it is much simpler to make an existing class hierarchy runnable because any class can be adapted to implement the run() method. A subclass of Thread cannot extend any other type, so application-specific code would have to be added to it rather than inherited.
Separating the Thread class from the Runnable implementation also avoids potential synchronization problems between the thread and the run() method. A separate Runnable generally gives greater flexibility in the way that runnable code is referenced and executed.

Q: When could I adapt the Thread class though?
A: It is always best to implement a Runnable type rather than extend a Thread. On that basis, the extension of the Thread class should only be considered in exceptional circumstances when the application is very simple, composed of few classes, where the interaction of threads is minimal and requires only minimal control over thread execution.

Q: What’s the difference between a thread’s start() and run() methods?
A: The separate start() and run() methods in the Thread class provide two ways to create threaded programs. The start() method starts the execution of the new thread and calls the run() method. The start() method returns immediately and the new thread normally continues until the run() method returns.
The Thread class’ run() method does nothing, so sub-classes should override the method with code to execute in the second thread. If a Thread is instantiated with a Runnable argument, the thread’s run() method executes the run() method of the Runnable object in the new thread instead.
Depending on the nature of your threaded program, calling the Thread run() method directly can give the same output as calling via the start() method, but in the latter case the code is actually executed in a new thread.

Q: Can I implement my own start() method?
A: The Thread start() method is not marked final, but should not be overridden. This method contains the code that creates a new executable thread and is very specialised. Your threaded application should either pass a Runnable type to a new Thread, or extend Thread and override the run() method.
Multi-threaded design questions

Q: If all methods are synchronized, is a class thread safe?
A: Even if all the methods of a class are synchronized, it may still be vulnerable to thread safety problems if it exposes non-final fields or its methods return mutable objects that could be manipulated by multiple threads. Non-final fields should be declared private and encapsulated with synchronization. Rather than return references to internal object fields, create an independent copy that has no relation to the original, known as a deep copy.
A deep copy of an object duplicates the content and state of the original object and all its constituent fields in such a way that none of its properties refer to instances in the original at any level.
These measures will help prevent uncontrolled access to the internal state of objects, but you must also ensure synchronization techniques are applied in a robust, consistent manner that will not cause deadlock or race conditions. It is generally better to use synchronized blocks than synchronized methods for performance reasons. Limit the extent of synchronized blocks and ensure they all use the same object monitor.

Q: How do I create a Runnable with inheritance?
A: To introduce a Runnable type to an existing class hierarchy, you need to create a sub-class that declares that it implements the Runnable interface, and provide a run method to fulfil the interface. This combination of interface and inheritance means that runnable implementations can be very minor extensions of existing classes


Oracle interview Questions

 

Oracle Concepts and Architecture

 Database Structures 

1. What are the components of physical database structure of Oracle database?
Oracle database is comprised of three types of files. One or more datafiles, two are more redo log files, and one or more control files.

2. What are the components of logical database structure of Oracle database? 
There are tablespaces and database's schema objects.

3. What is a tablespace? 
A database is divided into Logical Storage Unit called tablespaces. A tablespace is used to grouped related logical structures together.

4. What is SYSTEM tablespace and when is it created? 
Every Oracle database contains a tablespace named SYSTEM, which is automatically created when the database is created. The SYSTEM tablespace always contains the data dictionary tables for the entire database.

5. Explain the relationship among database, tablespace and data file. 
Each databases logically divided into one or more tablespaces one or more data files are explicitly created for each tablespace.

6. What is schema? 
A schema is collection of database objects of a user.

7. What are Schema Objects? 
Schema objects are the logical structures that directly refer to the database's data. Schema objects include tables, views, sequences, synonyms, indexes, clusters, database triggers, procedures, functions packages and database links.
  
8. Can objects of the same schema reside in different table spaces? 
Yes.

9. Can a tablespace hold objects from different schemes? 
Yes.

10. What is Oracle table? 
A table is the basic unit of data storage in an Oracle database. The tables of a database hold all of the user accessible data. Table data is stored in rows and columns.

11. What is an Oracle view? 
A view is a virtual table. Every view has a query attached to it. (The query is a SELECT statement that identifies the columns and rows of the table(s) the view uses.)

12. Do a view contain data? 
Views do not contain or store data.

13. Can a view based on another view? 
Yes.

14. What are the advantages of views? 
- Provide an additional level of table security, by restricting access to a predetermined set of rows and columns of a table.
- Hide data complexity.
- Simplify commands for the user.
- Present the data in a different perspective from that of the base table.
- Store complex queries.

15. What is an Oracle sequence? 
A sequence generates a serial list of unique numbers for numerical columns of a database's tables.

16.  What is a synonym?
A synonym is an alias for a table, view, sequence or program unit.

17. What are the types of synonyms? 
There are two types of synonyms private and public.

18. What is a private synonym? 
Only its owner can access a private synonym.

19. What is a public synonym? 
Any database user can access a public synonym.

20. What are synonyms used for? 
-  Mask the real name and owner of an object.

- Provide public access to an object

- Provide location transparency for tables, views or program units of a remote database.
- Simplify the SQL statements for database users.

21. What is an Oracle index? 
An index is an optional structure associated with a table to have direct access to rows, which can be created to increase the performance of data retrieval. Index can be created on one or more columns of a table.

22.  How are the index updates? 
Indexes are automatically maintained and used by Oracle. Changes to table data are automatically incorporated into all relevant indexes.

23. What are clusters? 
Clusters are groups of one or more tables physically stores together to share common columns and are often used together.

24. What is cluster key?
The related columns of the tables in a cluster are called the cluster key.

25. What is index cluster?
A cluster with an index on the cluster key.

26. What is hash cluster? 
A row is stored in a hash cluster based on the result of applying a hash function to the row's cluster key value. All rows with the same hash key value are stores together on disk.

27. When can hash cluster used? 
Hash clusters are better choice when a table is often queried with equality queries. For such queries the specified cluster key value is hashed. The resulting hash key value points directly to the area on disk that stores the specified rows.

28. What is database link? 
A database link is a named object that describes a "path" from one database to another.

29. What are the types of database links? 
Private database link, public database link & network database link.

30. What is private database link? 
Private database link is created on behalf of a specific user. A private database link can be used only when the owner of the link specifies a global object name in a SQL statement or in the definition of the owner's views or procedures.

31. What is public database link? 
Public database link is created for the special user group PUBLIC. A public database link can be used when any user in the associated database specifies a global object name in a SQL statement or object definition.

32.  What is network database link? 
Network database link is created and managed by a network domain service. A network database link can be used when any user of any database in the network specifies a global object name in a SQL statement or object definition.

33. What is data block? 
Oracle database's data is stored in data blocks. One data block corresponds to a specific number of bytes of physical database space on disk.

34. How to define data block size? 
A data block size is specified for each Oracle database when the database is created. A database users and allocated free database space in Oracle data blocks. Block size is specified in init.ora file and cannot be changed latter.

35. What is row chaining? 
In circumstances, all of the data for a row in a table may not be able to fit in the same data block. When this occurs, the data for the row is stored in a chain of data block (one or more) reserved for that segment.

36. What is an extent? 
An extent is a specific number of contiguous data blocks, obtained in a single allocation and used to store a specific type of information.

37.  What is a segment? 
A segment is a set of extents allocated for a certain logical structure.

38. What are the different types of segments?

Data segment, index segment, rollback segment and temporary segment.

39. What is a data segment? 
Each non-clustered table has a data segment. All of the table's data is stored in the extents of its data segment. Each cluster has a data segment. The data of every table in the cluster is stored in the cluster's data segment.

40. What is an index segment? 
Each index has an index segment that stores all of its data.

41. What is rollback segment? 
A database contains one or more rollback segments to temporarily store "undo" information.

42. What are the uses of rollback segment? 
To generate read-consistent database information during database recovery and to rollback uncommitted transactions by the users.

43. What is a temporary segment? 
Temporary segments are created by Oracle when a SQL statement needs a temporary work area to complete execution. When the statement finishes execution, the temporary segment extents are released to the system for future use.

44. What is a datafile? 
Every Oracle database has one or more physical data files. A database's data files contain all the database data. The data of logical database structures such as tables and indexes is physically stored in the data files allocated for a database.

45. What are the characteristics of data files? 
A data file can be associated with only one database. Once created a data file can't change size. One or more data files form a logical unit of database storage called a tablespace.

46. What is a redo log? 
The set of redo log files for a database is collectively known as the database redo log.

47. What is the function of redo log? 
The primary function of the redo log is to record all changes made to data.

48. What is the use of redo log information? 
The information in a redo log file is used only to recover the database from a system or media failure prevents database data from being written to a database's data files.

49. What does a control file contains? 
- Database name
- Names and locations of a database's files and redolog files.
- Time stamp of database creation.

50. What is the use of control file? 
When an instance of an Oracle database is started, its control file is used to identify the database and redo log files that must be opened for database operation to proceed. It is also used in database recovery.
Data Base Administration
  
51. What is a database instance? Explain.  
A database instance (Server) is a set of memory structure and background processes that access a set of database files. The processes can be shared by all of the users.

The memory structure that is used to store the most queried data from database. This helps up to improve database performance by decreasing the amount of I/O performed against data file.

52. What is Parallel Server? 
Multiple instances accessing the same database (only in multi-CPU environments)
  
53. What is a schema? 
The set of objects owned by user account is called the schema.

54.  What is an index? How it is implemented in Oracle database? 
An index is a database structure used by the server to have direct access of a row in a table. An index is automatically created when a unique of primary key constraint clause is specified in create table command

55. What are clusters? 
Group of tables physically stored together because they share common columns and are often used together is called cluster.

56. What is a cluster key? 
The related columns of the tables are called the cluster key.  The cluster key is indexed using a cluster index and its value is stored only once for multiple tables in the cluster.

57. What is the basic element of base configuration of an Oracle database? 
It consists of
            one or more data files.
            one or more control files.
            two or more redo log files.
The Database contains
            multiple users/schemas
     one or more rollback segments
            one or more tablespaces
            Data dictionary tables
            User objects (table,indexes,views etc.,)
The server that access the database consists of
            SGA (Database buffer, Dictionary Cache Buffers, Redo log buffers, Shared SQL pool)
            SMON (System MONito)
            PMON (Process MONitor)
            LGWR (LoG  Write)
            DBWR (Data Base Write)
            ARCH (ARCHiver)
            CKPT  (Check Point)
            RECO
            Dispatcher
            User Process with associated PGS

58. What is a deadlock? Explain. 
Two processes waiting to update the rows of a table, which are locked by other processes then deadlock arises.

In a database environment this will often happen because of not issuing the proper row lock commands. Poor design of front-end application may cause this situation and the performance of server will reduce drastically.

These locks will be released automatically when a commit/rollback operation performed or any one of this processes being killed externally.

Memory Management

  
59. What is SGA?  
The System Global Area in an Oracle database is the area in memory to facilitate the transfer of information between users. It holds the most recently requested structural information between users. It holds the most recently requested structural information about the database. The structure is database buffers, dictionary cache, redo log buffer and shared pool area.

60. What is a shared pool? 
The data dictionary cache is stored in an area in SGA called the shared pool. This will allow sharing of parsed SQL statements among concurrent users.

61. What is mean by Program Global Area (PGA)? 
It is area in memory that is used by a single Oracle user process.

62. What is a data segment? 
Data segment are the physical areas within a database block in which the data associated with tables and clusters are stored.

63. What are the factors causing the reparsing of SQL statements in SGA? 
Due to insufficient shared pool size. 
Monitor the ratio of the reloads takes place while executing SQL statements. If the ratio is greater than 1 then increase the SHARED_POOL_SIZE.

Database Logical & Physical Architecture


 64. What is Database Buffers? 
Database buffers are cache in the SGA used to hold the data blocks that are read from the data segments in the database such as tables, indexes and clusters DB_BLOCK_BUFFERS parameter in INIT.ORA decides the size.

65. What is dictionary cache? 
Dictionary cache is information about the database objects stored in a data dictionary table.

66. What is meant by recursive hints? 
Number of times processes repeatedly query the dictionary table is called recursive hints. It is due to the data dictionary cache is too small. By increasing the SHARED_POOL_SIZE parameter we can optimize the size of data dictionary cache.

67. What is redo log buffer? 
Changes made to the records are written to the on-line redo log files. So that they can be used in roll forward operations during database recoveries. Before writing them into the redo log files, they will first brought to redo log buffers in SGA and LGWR will write into files frequently. LOG_BUFFER parameter will decide the size.

68. How will you swap objects into a different table space for an existing database? 
- Export the user
- Perform import using the command imp system/manager file=export.dmp indexfile=newrite.sql. This will create all definitions into newfile.sql.
- Drop necessary objects.
- Run the script newfile.sql after altering the tablespaces.
- Import from the backup for the necessary objects.

69. List the Optional Flexible Architecture (OFA) of Oracle database?  How can we organize the tablespaces in Oracle database to have maximum performance? 
SYSTEM - Data dictionary tables.
DATA  - Standard operational tables.
DATA2- Static tables used for standard operations
INDEXES - Indexes for Standard operational tables.
INDEXES1 - Indexes of static tables used for standard operations.
TOOLS - Tools table.
TOOLS1 - Indexes for tools table.
RBS - Standard Operations Rollback Segments,
RBS1,RBS2 - Additional/Special Rollback segments.
TEMP - Temporary purpose tablespace
TEMP_USER - Temporary tablespace for users.
USERS - User tablespace.

70. How will you force database to use particular rollback segment? 
SET TRANSACTION USE ROLLBACK SEGMENT rbs_name.

71. What is meant by free extent? 
A free extent is a collection of continuous free blocks in tablespace. When a segment is dropped its extents are reallocated and are marked as free.

72.Which parameter in Storage clause will reduce number of rows per block? 
PCTFREE parameter 
Row size also reduces no of rows per block.

73. What is the significance of having storage clause? 
We can plan the storage for a table as how much initial extents are required, how much can be extended next, how much % should leave free for managing row updating, etc.,

74. How does Space allocation table place within a block? 
Each block contains entries as follows
Fixed block header
Variable block header
Row Header, row date (multiple rows may exists)
PCTEREE (% of free space for row updating in future)

75. What is the role of PCTFREE parameter is storage clause? 
This is used to reserve certain amount of space in a block for expansion of rows.

76. What is the OPTIMAL parameter? 
It is used to set the optimal length of a rollback segment.

77. What is the functionality of SYSTEM table space? 
To manage the database level transactions such as modifications of the data dictionary table that record information about the free space usage.

78. How will you create multiple rollback segments in a database? 
- Create a database, which implicitly creates a SYSTEM rollback segment in a SYSTEM tablespace. 
- Create a second rollback segment name R0 in the SYSTEM tablespace. 
- Make new rollback segment available (after shutdown, modify init.ora file and start database) 
- Create other tablespaces (RBS) for rollback segments. 
- Deactivate rollback segment R0 and activate the newly created rollback segments.

79. How the space utilization takes place within rollback segments? 
It will try to fit the transaction in a cyclic fashion to all existing extents. Once it found an extent is in use then it forced to acquire a new extent (number of extents is based on the optimal size)

80. Why query fails sometimes? 
Rollback segment dynamically extent to handle larger transactions entry loads. 
A single transaction may wipeout all available free space in the rollback segment tablespace. This prevents other user using rollback segments.

81. How will you monitor the space allocation? 
By querying DBA_SEGMENT table/view

82. How will you monitor rollback segment status? 
Querying the DBA_ROLLBACK_SEGS view

IN USE                           - Rollback Segment is on-line.
AVAILABLE                              - Rollback Segment available but not on-line.
OFF-LINE                       - Rollback Segment off-line
INVALID                        - Rollback Segment Dropped.
NEEDS RECOVERY                 - Contains data but need recovery or corrupted.
PARTLY AVAILABLE  - Contains data from an unresolved transaction involving a
                                           distributed database.

83. List the sequence of events when a large transaction that exceeds beyond its optimal value when an entry wraps and causes the rollback segment to expand into another extend. 
Transaction Begins. 
An entry is made in the RES header for new transactions entry 
Transaction acquires blocks in an extent of RBS 
The entry attempts to wrap into second extent. None is available, so that the RBS must extent. 
The RBS checks to see if it is part of its OPTIMAL size.
RBS chooses its oldest inactive segment.
Oldest inactive segment is eliminated.
RBS extents
The data dictionary tables for space management are updated.
Transaction Completes.

84. How can we plan storage for very large tables? 
Limit the number of extents in the table
Separate table from its indexes.
Allocate sufficient temporary storage.

85. How will you estimate the space required by a non-clustered table? 
Calculate the total header size
Calculate the available data space per data block
Calculate the combined column lengths of the average row
Calculate the total average row size.
Calculate the average number rows that can fit in a block
Calculate the number of blocks and bytes required for the table. 
After arriving the calculation, add 10 % additional space to calculate the initial extent size for a working table.

86. It is possible to use raw devices as data files and what are the advantages over file system files? 
Yes. 
The advantages over file system files are that I/O will be improved because Oracle is bye-passing the kernel which writing into disk. Disk corruption will be very less.

87. What is a Control file? 
Database's overall physical architecture is maintained in a file called control file. It will be used to maintain internal consistency and guide recovery operations. Multiple copies of control files are advisable.

88. How to implement the multiple control files for an existing database? 
Shutdown the database
Copy one of the existing control file to new location
Edit Config ora file by adding new control filename
Restart the database.

89. What is redo log file mirroring?  How can be achieved? 
Process of having a copy of redo log files is called mirroring. 
This can be achieved by creating group of log files together, so that LGWR will automatically writes them to all the members of the current on-line redo log group. If any one group fails then database automatically switch over to next group. It degrades performance.

90. What is advantage of having disk shadowing / mirroring? 
Shadow set of disks save as a backup in the event of disk failure. In most operating systems if any disk failure occurs it automatically switchover to place of failed disk. 
Improved performance because most OS support volume shadowing can direct file I/O request to use the shadow set of files instead of the main set of files. This reduces I/O load on the main set of disks.

91. What is use of rollback segments in Oracle database? 
They allow the database to maintain read consistency between multiple transactions.

92. What is a rollback segment entry? 
It is the set of before image data blocks that contain rows that are modified by a transaction.
Each rollback segment entry must be completed within one rollback segment. 
A single rollback segment can have multiple rollback segment entries.

93. What is hit ratio? 
It is a measure of well the data cache buffer is handling requests for data. 
Hit Ratio = (Logical Reads - Physical Reads - Hits Misses)/ Logical Reads.

94. When will be a segment released? 
When Segment is dropped.
When Shrink (RBS only)
When truncated (TRUNCATE used with drop storage option)

95. What are disadvantages of having raw devices? 
We should depend on export/import utility for backup/recovery (fully reliable) 
The tar command cannot be used for physical file backup, instead we can use dd command, which is less flexible and has limited recoveries.

96. List the factors that can affect the accuracy of the estimations? 
- The space used transaction entries and deleted records, does not become free immediately after completion due to delayed cleanout.  
- Trailing nulls and length bytes are not stored. 
- Inserts of, updates to and deletes of rows as well as columns larger than a single data block, can cause fragmentation a chained row pieces.
  

Database Security & Administration

  
97. What is user Account in Oracle database? 
A user account is not a physical structure in database but it is having important relationship to the objects in the database and will be having certain privileges.

98. How will you enforce security using stored procedures? 
Don't grant user access directly to tables within the application. 
Instead grant the ability to access the procedures that access the tables. 
When procedure executed it will execute the privilege of procedures owner. Users cannot access tables except via the procedure.

99. What are the dictionary tables used to monitor a database space?

DBA_FREE_SPACE
DBA_SEGMENTS
DBA_DATA_FILES.
  

SQL*Plus Statements

 100. What are the types of SQL statement?

Data Definition Language: CREATE, ALTER, DROP, TRUNCATE, REVOKE, NO AUDIT & COMMIT.
Data Manipulation Language: INSERT, UPDATE, DELETE, LOCK TABLE, EXPLAIN PLAN & SELECT.
Transactional Control: COMMIT & ROLLBACK
Session Control: ALTERSESSION & SET ROLE
System Control: ALTER SYSTEM.

101. What is a transaction? 
Transaction is logical unit between two commits and commit and rollback.

102. What is difference between TRUNCATE & DELETE? 
TRUNCATE commits after deleting entire table i.e., cannot be rolled back.
Database triggers do not fire on TRUNCATE 
DELETE allows the filtered deletion. Deleted records can be rolled back or committed.
Database triggers fire on DELETE.

103. What is a join? Explain the different types of joins? 
Join is a query, which retrieves related columns or rows from multiple tables. 
Self Join - Joining the table with itself.
Equi Join - Joining two tables by equating two common columns.
Non-Equi Join - Joining two tables by equating two common columns.
Outer Join - Joining two tables in such a way that query can also retrieve rows that do not have corresponding join value in the other table.

104. What is the sub-query? 
Sub-query is a query whose return values are used in filtering conditions of the main query.

105. What is correlated sub-query? 
Correlated sub-query is a sub-query, which has reference to the main query.

106. Explain CONNECT BY PRIOR? 
Retrieves rows in hierarchical order eg.  
select empno, ename from emp where.

107. Difference between SUBSTR and INSTR?

INSTR (String1, String2 (n, (m)),
INSTR returns the position of the m-th occurrence of the string 2 in string1. The search begins from nth position of string1.

SUBSTR (String1 n, m)
SUBSTR returns a character string of size m in string1, starting from n-th position of string1.

108. Explain UNION, MINUS, UNION ALL and INTERSECT? 
INTERSECT   - returns all distinct rows selected by both queries.
MINUS            - returns all distinct rows selected by the first query but not by the second.
UNION            - returns all distinct rows selected by either query
UNION ALL    - returns all rows selected by either query, including all duplicates.

109. What is ROWID? 
ROWID is a pseudo column attached to each row of a table. It is 18 characters long, blockno, rownumber are the components of ROWID.

110. What is the fastest way of accessing a row in a table?

Using ROWID.
CONSTRAINTS

111. What is an integrity constraint? 
Integrity constraint is a rule that restricts values to a column in a table.

112. What is referential integrity constraint? 
Maintaining data integrity through a set of rules that restrict the values of one or more columns of the tables based on the values of primary key or unique key of the referenced table.

113. What is the usage of SAVEPOINTS?  
SAVEPOINTS are used to subdivide a transaction into smaller parts. It enables rolling back part of a transaction. Maximum of five save points are allowed.

114.  What is ON DELETE CASCADE? 
When ON DELETE CASCADE is specified Oracle maintains referential integrity by automatically removing dependent foreign key values if a referenced primary or unique key value is removed.

115. What are the data types allowed in a table? 
CHAR, VARCHAR2, NUMBER, DATE, RAW, LONG and LONG RAW.

116. What is difference between CHAR and VARCHAR2?  What is the maximum SIZE allowed for each type?

CHAR pads blank spaces to the maximum length.
VARCHAR2 does not pad blank spaces.
For CHAR the maximum length is 255 and 2000 for VARCHAR2.

117.  How many LONG columns are allowed in a table? Is it possible to use LONG columns in WHERE clause or ORDER BY? 
Only one LONG column is allowed. It is not possible to use LONG column in WHERE or ORDER BY clause.

118. What are the pre-requisites to modify datatype of a column and to add a column with NOT NULL constraint? 
 - To modify the datatype of a column the column must be empty.
 - To add a column with NOT NULL constrain, the table must be empty.

119. Where the integrity constraints are stored in data dictionary? 
The integrity constraints are stored in USER_CONSTRAINTS.

120. How will you activate/deactivate integrity constraints? 
The integrity constraints can be enabled or disabled by ALTER TABLE ENABLE CONSTRAINT / DISABLE CONSTRAINT.

121. If unique key constraint on DATE column is created, will it validate the rows that are inserted with SYSDATE? 
It won't, Because SYSDATE format contains time attached with it.

122. What is a database link? 
Database link is a named path through which a remote database can be accessed.

123. How to access the current value and next value from a sequence? Is it possible to access the current value in a session before accessing next value? 
Sequence name CURRVAL, sequence name NEXTVAL. It is not possible. Only if you access next value in the session, current value can be accessed.

124. What is CYCLE/NO CYCLE in a Sequence? 
CYCLE specifies that the sequence continue to generate values after reaching either maximum or minimum value. After pan-ascending sequence reaches its maximum value, it generates its minimum value. After a descending sequence reaches its minimum, it generates its maximum.

NO CYCLE specifies that the sequence cannot generate more values after reaching its maximum or minimum value.

125. What are the advantages of VIEW? 
- To protect some of the columns of a table from other users.
- To hide complexity of a query.
- To hide complexity of calculations.

126. Can a view be updated/inserted/deleted? If Yes - under what conditions? 
A View can be updated/deleted/inserted if it has only one base table if the view is based on columns from one or more tables then insert, update and delete is not possible.

127. If a view on a single base table is manipulated will the changes be reflected on the base table? 
If changes are made to the tables and these tables are the base tables of a view, then the changes will be reference on the view.

Oracle Interview Questions and Answers: SQL

1.      To see current user name Ã  SQL> show user;
2.      Change SQL prompt name Ã  SQL> set sqlprompt “Manimara > “
3.      Switch to DOS prompt Ã  SQL> host

4.      How do I eliminate the duplicate rows ?
 SQL> delete from table_name where rowid not in (select max(rowid) from table group by duplicate_values_field_name);
or
SQL> delete duplicate_values_field_name dv from table_name ta where rowid <(select min(rowid)  from table_name tb where ta.dv=tb.dv);
Example.
Table Emp
Empno Ename
101               Scott
102               Jiyo
103               Millor
104               Jiyo
105               Smith
delete ename from emp a where rowid < ( select min(rowid) from emp b where a.ename = b.ename);
The output like,
Empno Ename
101               Scott
102               Millor
103               Jiyo
104               Smith

5.      How do I display row number with records?
To achive this use rownum pseudocolumn with query, like
SQL> select rownum, ename from emp;
Output:
1                    Scott
2                    Millor
3                    Jiyo
4                    Smith

6.      Display the records between two range
select rownum, empno, ename  from emp  where  rowid in
 (select rowid from emp where rownum <=&upto
 minus
 select rowid from emp where rownum<&Start);
Enter value for upto: 10
Enter value for Start: 7

   ROWNUM     EMPNO ENAME
--------- --------- ----------
        1      7782 CLARK
        2      7788 SCOTT
        3      7839 KING
        4      7844 TURNER

7.      I know the nvl function only allows the same data type(ie. number or char or date Nvl(comm, 0)), if commission is null then the text “Not Applicable”  want to display, instead of blank space. How do I write the query?
 SQL> select nvl(to_char(comm.),'NA') from emp;
Output :
NVL(TO_CHAR(COMM),'NA')
-----------------------
NA
300
500
NA
1400
NA
NA

8.      Oracle cursor : Implicit & Explicit cursors
Oracle uses work areas called private SQL areas to create SQL statements.
PL/SQL construct to identify each and every work are used, is called as Cursor.
For SQL queries returning a single row, PL/SQL declares all implicit cursors.
For queries that returning more than one row, the cursor needs to be explicitly declared.

9.      Explicit Cursor attributes
 There are four cursor attributes used in Oracle
cursor_name%Found, cursor_name%NOTFOUND, cursor_name%ROWCOUNT, cursor_name%ISOPEN

10.  Implicit Cursor attributes
 Same as explicit cursor but prefixed by the word SQL

SQL%Found, SQL%NOTFOUND, SQL%ROWCOUNT, SQL%ISOPEN
Tips : 1. Here SQL%ISOPEN is false, because oracle automatically closed the implicit cursor after executing SQL statements.
       : 2.  All are Boolean attributes.

11.  Find out nth highest salary from emp table
 SELECT DISTINCT (a.sal) FROM EMP A WHERE &N = (SELECT COUNT (DISTINCT (b.sal)) FROM EMP B WHERE a.sal<=b.sal);

Enter value for n: 2
      SAL
---------
     3700

12.  To view installed Oracle version information
 SQL> select banner from v$version;

13.  Display the number value in Words
 SQL> select sal, (to_char(to_date(sal,'j'), 'jsp'))
from emp;
the output like,

      SAL (TO_CHAR(TO_DATE(SAL,'J'),'JSP'))
--------- -----------------------------------------------------
      800 eight hundred
     1600 one thousand six hundred
     1250 one thousand two hundred fifty
If you want to add some text like,
Rs. Three Thousand only.
SQL> select sal  "Salary ",
 (' Rs. '|| (to_char(to_date(sal,'j'), 'Jsp'))|| ' only.'))
 "Sal in Words" from emp
/
Salary  Sal in Words
------- ------------------------------------------------------
    800  Rs. Eight Hundred only.
   1600  Rs. One Thousand Six Hundred only.
   1250  Rs. One Thousand Two Hundred Fifty only.

14.  Display Odd/ Even number of records
 Odd number of records:
select * from emp where (rowid,1) in (select rowid, mod(rownum,2) from emp);
1
3
5
Even number of records:
select * from emp where (rowid,0) in (select rowid, mod(rownum,2) from emp)
2
4
6

15.  Which date function returns number value?
 months_between

16.  Any three PL/SQL Exceptions?
 Too_many_rows, No_Data_Found, Value_Error, Zero_Error, Others

17.  What are PL/SQL Cursor Exceptions?
 Cursor_Already_Open, Invalid_Cursor

18.  Other way to replace query result null value with a text
 SQL> Set NULL ‘N/A’
to reset SQL> Set NULL ‘’

19.   What are the more common pseudo-columns?
 SYSDATE, USER , UID, CURVAL, NEXTVAL, ROWID, ROWNUM

20.   What is the output of SIGN function?
 1 for positive value,
0 for Zero,
-1 for Negative value.

21.  What is the maximum number of triggers, can apply to a single table?
 12 triggers.






PL/SQL interview Questions Database

  1. Which of the following statements is true about implicit cursors?
    1. Implicit cursors are used for SQL statements that are not named.
    2. Developers should use implicit cursors with great care.
    3. Implicit cursors are used in cursor for loops to handle data processing.
    4. Implicit cursors are no longer a feature in Oracle.
  2. Which of the following is not a feature of a cursor FOR loop?
    1. Record type declaration.
    2. Opening and parsing of SQL statements.
    3. Fetches records from cursor.
    4. Requires exit condition to be defined.
  3. A developer would like to use referential datatype declaration on a variable. The variable name is EMPLOYEE_LASTNAME, and the corresponding table and column is EMPLOYEE, and LNAME, respectively. How would the developer define this variable using referential datatypes?
    1. Use employee.lname%type.
    2. Use employee.lname%rowtype.
    3. Look up datatype for EMPLOYEE column on LASTNAME table and use that.
    4. Declare it to be type LONG.
  4. Which three of the following are implicit cursor attributes?
    1. %found
    2. %too_many_rows
    3. %notfound
    4. %rowcount
    5. %rowtype
  5. If left out, which of the following would cause an infinite loop to occur in a simple loop?
    1. LOOP
    2. END LOOP
    3. IF-THEN
    4. EXIT
  6. Which line in the following statement will produce an error?
    1. cursor action_cursor is
    2. select name, rate, action
    3. into action_record
    4. from action_table;
    5. There are no errors in this statement.
  7. The command used to open a CURSOR FOR loop is
    1. open
    2. fetch
    3. parse
    4. None, cursor for loops handle cursor opening implicitly.
  8. What happens when rows are found using a FETCH statement
    1. It causes the cursor to close
    2. It causes the cursor to open
    3. It loads the current row values into variables
    4. It creates the variables to hold the current row values
  9. Read the following code:
10.  CREATE OR REPLACE PROCEDURE find_cpt
11.  (v_movie_id {Argument Mode} NUMBER, v_cost_per_ticket {argument mode} NUMBER)
12.  IS
13.  BEGIN
14.    IF v_cost_per_ticket  > 8.5 THEN
15.  SELECT  cost_per_ticket
16.  INTO            v_cost_per_ticket
17.  FROM            gross_receipt
18.  WHERE   movie_id = v_movie_id;
19.    END IF;
20.  END;
Which mode should be used for V_COST_PER_TICKET?
    1. IN
    2. OUT
    3. RETURN
    4. IN OUT
  1. Read the following code:
22.  CREATE OR REPLACE TRIGGER update_show_gross
23.        {trigger information}
24.       BEGIN
25.        {additional code}
26.       END;
The trigger code should only execute when the column, COST_PER_TICKET, is greater than $3. Which trigger information will you add?
    1. WHEN (new.cost_per_ticket > 3.75)
    2. WHEN (:new.cost_per_ticket > 3.75
    3. WHERE (new.cost_per_ticket > 3.75)
    4. WHERE (:new.cost_per_ticket > 3.75)
  1. What is the maximum number of handlers processed before the PL/SQL block is exited when an exception occurs?
    1. Only one
    2. All that apply
    3. All referenced
    4. None
  2. For which trigger timing can you reference the NEW and OLD qualifiers?
    1. Statement and Row
    2. Statement only
    3. Row only
    4. Oracle Forms trigger
  3. Read the following code:
30.  CREATE OR REPLACE FUNCTION get_budget(v_studio_id IN NUMBER)
RETURN number IS
 
       
v_yearly_budget NUMBER;
 
       
BEGIN
       SELECT  yearly_budget
       INTO            v_yearly_budget
       FROM            studio
       WHERE   id = v_studio_id;
 
       
       RETURN v_yearly_budget;
END;
Which set of statements will successfully invoke this function within SQL*Plus?
    1. VARIABLE g_yearly_budget NUMBER
      EXECUTE g_yearly_budget := GET_BUDGET(11);
    2. VARIABLE g_yearly_budget NUMBER
      EXECUTE :g_yearly_budget := GET_BUDGET(11);
    3. VARIABLE :g_yearly_budget NUMBER
      EXECUTE :g_yearly_budget := GET_BUDGET(11);
    4. VARIABLE g_yearly_budget NUMBER
      :g_yearly_budget := GET_BUDGET(11);
31.  CREATE OR REPLACE PROCEDURE update_theater
32.  (v_name IN VARCHAR v_theater_id IN NUMBER) IS
33.  BEGIN
34.         UPDATE  theater
35.         SET             name = v_name
36.         WHERE   id = v_theater_id;
37.  END update_theater;
  1. When invoking this procedure, you encounter the error:
ORA-000: Unique constraint(SCOTT.THEATER_NAME_UK) violated.
How should you modify the function to handle this error?
    1. An user defined exception must be declared and associated with the error code and handled in the EXCEPTION section.
    2. Handle the error in EXCEPTION section by referencing the error code directly.
    3. Handle the error in the EXCEPTION section by referencing the UNIQUE_ERROR predefined exception.
    4. Check for success by checking the value of SQL%FOUND immediately after the UPDATE statement.
  1. Read the following code:
40.  CREATE OR REPLACE PROCEDURE calculate_budget IS
41.  v_budget        studio.yearly_budget%TYPE;
42.  BEGIN
43.         v_budget := get_budget(11);
44.         IF v_budget < 30000
45.                        THEN
46.                 set_budget(11,30000000);
47.         END IF;
48.  END;
You are about to add an argument to CALCULATE_BUDGET. What effect will this have?
    1. The GET_BUDGET function will be marked invalid and must be recompiled before the next execution.
    2. The SET_BUDGET function will be marked invalid and must be recompiled before the next execution.
    3. Only the CALCULATE_BUDGET procedure needs to be recompiled.
    4. All three procedures are marked invalid and must be recompiled.
  1. Which procedure can be used to create a customized error message?
    1. RAISE_ERROR
    2. SQLERRM
    3. RAISE_APPLICATION_ERROR
    4. RAISE_SERVER_ERROR
  2. The CHECK_THEATER trigger of the THEATER table has been disabled. Which command can you issue to enable this trigger?
    1. ALTER TRIGGER check_theater ENABLE;
    2. ENABLE TRIGGER check_theater;
    3. ALTER TABLE check_theater ENABLE check_theater;
    4. ENABLE check_theater;
  3. Examine this database trigger
52.  CREATE OR REPLACE TRIGGER prevent_gross_modification
53.  {additional trigger information}
54.  BEGIN
55.         IF TO_CHAR(sysdate, DY) = MON
56.         THEN
57.         RAISE_APPLICATION_ERROR(-20000,Gross receipts cannot be deleted on Monday);
58.         END IF;
59.  END;
This trigger must fire before each DELETE of the GROSS_RECEIPT table. It should fire only once for the entire DELETE statement. What additional information must you add?
    1. BEFORE DELETE ON gross_receipt
    2. AFTER DELETE ON gross_receipt
    3. BEFORE (gross_receipt DELETE)
    4. FOR EACH ROW DELETED FROM gross_receipt
  1. Examine this function:
61.  CREATE OR REPLACE FUNCTION set_budget
62.  (v_studio_id IN NUMBER, v_new_budget IN NUMBER) IS
63.  BEGIN
64.         UPDATE  studio
65.         SET             yearly_budget = v_new_budget
       WHERE   id = v_studio_id;
 
       
       IF SQL%FOUND THEN
               RETURN TRUEl;
       ELSE
               RETURN FALSE;
       END IF;
 
       
       COMMIT;
END;
Which code must be added to successfully compile this function?
    1. Add RETURN right before the IS keyword.
    2. Add RETURN number right before the IS keyword.
    3. Add RETURN boolean right after the IS keyword.
    4. Add RETURN boolean right before the IS keyword.
  1. Under which circumstance must you recompile the package body after recompiling the package specification?
    1. Altering the argument list of one of the package constructs
    2. Any change made to one of the package constructs
    3. Any SQL statement change made to one of the package constructs
    4. Removing a local variable from the DECLARE section of one of the package constructs
  2. Procedure and Functions are explicitly executed. This is different from a database trigger. When is a database trigger executed?
    1. When the transaction is committed
    2. During the data manipulation statement
    3. When an Oracle supplied package references the trigger
    4. During a data manipulation statement and when the transaction is committed
  3. Which Oracle supplied package can you use to output values and messages from database triggers, stored procedures and functions within SQL*Plus?
    1. DBMS_DISPLAY
    2. DBMS_OUTPUT
    3. DBMS_LIST
    4. DBMS_DESCRIBE
  4. What occurs if a procedure or function terminates with failure without being handled?
    1. Any DML statements issued by the construct are still pending and can be committed or rolled back.
    2. Any DML statements issued by the construct are committed
    3. Unless a GOTO statement is used to continue processing within the BEGIN section, the construct terminates.
    4. The construct rolls back any DML statements issued and returns the unhandled exception to the calling environment.
  5. Examine this code
71.  BEGIN
72.         theater_pck.v_total_seats_sold_overall := theater_pck.get_total_for_year;
73.  END;
For this code to be successful, what must be true?
    1. Both the V_TOTAL_SEATS_SOLD_OVERALL variable and the GET_TOTAL_FOR_YEAR function must exist only in the body of the THEATER_PCK package.
    2. Only the GET_TOTAL_FOR_YEAR variable must exist in the specification of the THEATER_PCK package.
    3. Only the V_TOTAL_SEATS_SOLD_OVERALL variable must exist in the specification of the THEATER_PCK package.
    4. Both the V_TOTAL_SEATS_SOLD_OVERALL variable and the GET_TOTAL_FOR_YEAR function must exist in the specification of the THEATER_PCK package.
  1. A stored function must return a value based on conditions that are determined at runtime. Therefore, the SELECT statement cannot be hard-coded and must be created dynamically when the function is executed. Which Oracle supplied package will enable this feature?
    1. DBMS_DDL
    2. DBMS_DML
    3. DBMS_SYN
    4. DBMS_SQL



Database management interview questions Database

1. What is a Cartesian product? What causes it?
Expected answer:
A Cartesian product is the result of an unrestricted join of two or more tables. The result set of a three table Cartesian product will have x * y * z number of rows where x, y, z correspond to the number of rows in each table involved in the join. It is causes by specifying a table in the FROM clause without joining it to another table.
2. What is an advantage to using a stored procedure as opposed to passing an SQL query from an application.
Expected answer:
A stored procedure is pre-loaded in memory for faster execution. It allows the DBMS control of permissions for security purposes. It also eliminates the need to recompile components when minor changes occur to the database.
3. What is the difference of a LEFT JOIN and an INNER JOIN statement?
Expected answer:
A LEFT JOIN will take ALL values from the first declared table and matching values from the second declared table based on the column the join has been declared on. An INNER JOIN will take only matching values from both tables
4. When a query is sent to the database and an index is not being used, what type of execution is taking place?
Expected answer:
A table scans.
5. What are the pros and cons of using triggers?
Expected answer:
A trigger is one or more statements of SQL that are being executed in event of data modification in a table to which the trigger belongs.
Triggers enhance the security, efficiency, and standardization of databases.
Triggers can be beneficial when used:
– to check or modify values before they are actually updated or inserted in the database. This is useful if you need to transform data from the way the user sees it to some internal database format.
– to run other non-database operations coded in user-defined functions
– to update data in other tables. This is useful for maintaining relationships between data or in keeping audit trail information.
– To check against other data in the table or in other tables. This is useful to ensure data integrity when referential integrity constraints aren’t appropriate, or when table check constraints limit checking to the current table only.



































Hibernate interview Questions
1. What is ORM?
ORM stands for object/relational mapping. ORM is the automated persistence of objects in a Java application to the tables in a relational database.

2.What does ORM consists of ?
An ORM solution consists of the following four pieces:
• API for performing basic CRUD operations
• API to express queries referring to classes
• Facilities to specify metadata
• Optimization facilities : dirty checking, lazy associations fetching

3. What are the ORM levels?
The ORM levels are:
• Pure relational (stored procedure.)
• Light objects mapping (JDBC)
• Medium object mapping
• Full object Mapping (composition, inheritance, polymorphism, persistence by reachability

4. What is Hibernate?
Hibernate is a pure Java object-relational mapping (ORM) and persistence framework that allows you to map plain old Java objects to relational database tables using (XML) configuration files.Its purpose is to relieve the developer from a significant amount of relational data persistence-related programming tasks.

5. Why do you need ORM tools like hibernate?
The main advantage of ORM like hibernate is that it shields developers from messy SQL. Apart from this, ORM provides following benefits:
• Improved productivity
• High-level object-oriented API
• Less Java code to write
• No SQL to write
• Improved performance
• Sophisticated caching
• Lazy loading
• Eager loading
• Improved maintainability
• A lot less code to write
• Improved portability
• ORM framework generates database-specific SQL for you

6. What Does Hibernate Simplify?
Hibernate simplifies:
• Saving and retrieving your domain objects
• Making database column and table name changes
• Centralizing pre save and post retrieve logic
• Complex joins for retrieving related items
• Schema creation from object model

7. What are Callback interfaces?
Callback interfaces allow the application to receive a notification when something interesting happens to an object—for example, when an object is loaded, saved, or deleted. Hibernate applications don't need to implement these callbacks, but they're useful for implementing certain kinds of generic functionality.

8. What are the most common methods of Hibernate configuration?
The most common methods of Hibernate configuration are:
• Programmatic configuration
• XML configuration (hibernate.cfg.xml)

9. What are the types of Hibernate instance states ?
Three types of instance states:
• Transient -The instance is not associated with any persistence context
• Persistent -The instance is associated with a persistence context
• Detached -The instance was associated with a persistence context which has been closed – currently not associated

10. What are the Core interfaces are of Hibernate framework?
The five core interfaces are used in just about every Hibernate application. Using these interfaces, you can store and retrieve persistent objects and control transactions.
• Session interface
• SessionFactory interface
• Configuration interface
• Transaction interface
• Query and Criteria interfaces

11. What role does the Session interface play in Hibernate?
The Session interface is the primary interface used by Hibernate applications. It is a single-threaded, short-lived object representing a conversation between the application and the persistent store. It allows you to create query objects to retrieve persistent objects.

Session session = sessionFactory.openSession();
Session interface role:
• Wraps a JDBC connection
• Factory for Transaction
• Holds a mandatory (first-level) cache of persistent objects, used when navigating the object graph or looking up objects by identifier
• 12.What role does the SessionFactory interface play in Hibernate?
• The application obtains Session instances from a SessionFactory. There is typically a single SessionFactory for the whole applicationÃ¥¹¼reated during application initialization. The SessionFactory caches generate SQL statements and other mapping metadata that Hibernate uses at runtime. It also holds cached data that has been read in one unit of work and may be reused in a future unit of work

SessionFactory sessionFactory = configuration.buildSessionFactory();

12. What is the general flow of Hibernate communication with RDBMS?
The general flow of Hibernate communication with RDBMS is :
• Load the Hibernate configuration file and create configuration object. It will automatically load all hbm mapping files
• Create session factory from configuration object
• Get one session from this session factory
• Create HQL Query
• Execute query to get list containing Java objects

13. What is Hibernate Query Language (HQL)?
Hibernate offers a query language that embodies a very powerful and flexible mechanism to query, store, update, and retrieve objects from a database. This language, the Hibernate query Language (HQL), is an object-oriented extension to SQL.

14. How do you map Java Objects with Database tables?
• First we need to write Java domain objects (beans with setter and getter).
• Write hbm.xml, where we map java class to table and database columns to Java class variables.

15. What’s the difference between load () and get()?
load() vs. get() :-
load() get()
Only use the load() method if you are sure that the object exists. If you are not sure that the object exists, then use one of the get() methods.
load() method will throw an exception if the unique id is not found in the database. get() method will return null if the unique id is not found in the database.
load() just returns a proxy by default and database won’t be hit until the proxy is first invoked. get() will hit the database immediately.

16. What is the difference between and merge and update ?
Use update() if you are sure that the session does not contain an already persistent instance with the same identifier, and merge() if you want to merge your modifications at any time without consideration of the state of the session.

17. Define cascade and inverse option in one-many mapping?
cascade - enable operations to cascade to child entities.
cascade="all|none|save-update|delete|all-delete-orphan"

inverse - mark this collection as the "inverse" end of a bidirectional association.
inverse="true|false"
Essentially "inverse" indicates which end of a relationship should be ignored, so when persisting a parent who has a collection of children, should you ask the parent for its list of children, or ask the children who the parents are?

18. What do you mean by Named – SQL query?
Named SQL queries are defined in the mapping xml document and called wherever required.
Example:


SELECT emp.EMP_ID AS {emp.empid},
emp.EMP_ADDRESS AS {emp.address},
emp.EMP_NAME AS {emp.name}
FROM Employee EMP WHERE emp.NAME LIKE :name


Invoke Named Query :
List people = session.getNamedQuery("empdetails")
.setString("TomBrady", name)
.setMaxResults(50)
.list();

19. How do you invoke Stored Procedures?






{ ? = call selectAllEmployees() }



20. Explain Criteria API
Criteria are a simplified API for retrieving entities by composing Criterion objects. This is a very convenient approach for functionality like "search" screens where there is a variable number of conditions to be placed upon the result set.
Example:
List employees = session.createCriteria(Employee.class)
.add(Restrictions.like("name", "a%") )
.add(Restrictions.like("address", "Boston"))
.addOrder(Order.asc("name") )
.list();

21. Define HibernateTemplate?
org.springframework.orm.hibernate.HibernateTemplate is a helper class which provides different methods for querying/retrieving data from the database. It also converts checked HibernateExceptions into unchecked DataAccessExceptions.

22. What are the benefits does HibernateTemplate provide?
The benefits of HibernateTemplate are :
• HibernateTemplate, a Spring Template class simplifies interactions with Hibernate Session.
• Common functions are simplified to single method calls.
• Sessions are automatically closed.
• Exceptions are automatically caught and converted to runtime exceptions.

23. How do you switch between relational databases without code changes?
Using Hibernate SQL Dialects , we can switch databases. Hibernate will generate appropriate hql queries based on the dialect defined.

24. What is automatic dirty checking?
Automatic dirty checking is a feature that saves us the effort of explicitly asking Hibernate to update the database when we modify the state of an object inside a transaction.

25. What is transactional write-behind?
Hibernate uses a sophisticated algorithm to determine an efficient ordering that avoids database foreign key constraint violations but is still sufficiently predictable to the user. This feature is called transactional write-behind.

26. If you want to see the Hibernate generated SQL statements on console, what should we do?
In Hibernate configuration file set as follows:
true

27. What are derived properties?
The properties that are not mapped to a column, but calculated at runtime by evaluation of an expression are called derived properties. The expression can be defined using the formula attribute of the element.

28. What is component mapping in Hibernate?
• A component is an object saved as a value, not as a reference
• A component can be saved directly without needing to declare interfaces or identifier properties
• Required to define an empty constructor
• Shared references not supported

29. What is the difference between sorted and ordered collection in hibernate?
sorted collection vs. order collection :-
sorted collection order collection
A sorted collection is sorting a collection by utilizing the sorting features provided by the Java collections framework. The sorting occurs in the memory of JVM which running Hibernate, after the data being read from database using java comparator. Order collection is sorting a collection by specifying the order-by clause for sorting this collection when retrieval.
If your collection is not large, it will be more efficient way to sort it. If your collection is very large, it will be more efficient way to sort it .

30. What are the Collection types in Hibernate?
• Bag ,Set ,List ,Array ,Map

31. What are the ways to express joins in HQL?
HQL provides four ways of expressing (inner and outer) joins:-
• An implicit association join
• An ordinary join in the FROM clause
• A fetch join in the FROM clause.
• A theta-style join in the WHERE clause.

32. What is Hibernate proxy?
The proxy attribute enables lazy initialization of persistent instances of the class. Hibernate will initially return CGLIB proxies which implement the named interface. The actual persistent object will be loaded when a method of the proxy is invoked.

33. How can Hibernate be configured to access an instance variable directly and not through a setter method?
By mapping the property with access="field" in Hibernate metadata. This forces hibernate to bypass the setter method and access the instance variable directly while initializing a newly loaded object.

34. How can a whole class be mapped as immutable?
Mark the class as mutable="false" (Default is true). This specifies that instances of the class are (not) mutable. Immutable classes may not be updated or deleted by the application.

35. What is the use of dynamic-insert and dynamic-update attributes in a class mapping?
Criteria are a simplified API for retrieving entities by composing Criterion objects. This is a very convenient approach for functionality like "search" screens where there are a variable number of conditions to be placed upon the result set.
• dynamic-update (defaults to false): Specifies that UPDATE SQL should be generated ``at runtime and contain only those columns whose values have changed
• dynamic-insert (defaults to false): Specifies that INSERT SQL should be generated ``at runtime and contain only the columns whose values are not null.

36. What do you mean by fetching strategy?
A fetching strategy is the strategy Hibernate will use for retrieving associated objects if the application needs to navigate the association. Fetch strategies may be declared in the O/R mapping metadata, or over-ridden by a particular HQL or Criteria query.

37. What are the types of inheritance models in Hibernate?
There are three types of inheritance models in Hibernate:
• Table per class hierarchy
• Table per subclass
• Table per concrete class