Documente Academic
Documente Profesional
Documente Cultură
com
Core Java
Java Material Interview Reference
Q) OOPS concepts Polymorphism Ability to take more than one form, In java we achieve this using Method Overloading (compile time polymorphism), Method overriding (runtime polymorphism) Inheritance Is the process by which one object acquires the properties of another object. Encapsulation Wrapping of data and function into a single unit called encapsulation. Ex:- all java programs. Abstraction Nothing but representing the essential futures without including background details. Dynamicbinding Code associated with a given procedural call is not known until the time of the call at runtime. Dynamic binding is nothing but late binding. Q) class & object? class class is a Template that describes the Kind of State(The Instance Variables) and Behavior (Methods) class is a blue print of an object component means u can use a piece of code like an independent piece.like servlet,EJB...etc Object instance of class u can reuse it in any application Q) System.out.println() println() is a methd of java.io.printWriter. out is an instance variable of java.lang.System class. Q) Transient & volatile Transient --> the object or variable will not persist. Volatile --> value will be changed unexpectedly by the other part of the program. Q) Access Specifiers & Access modifiers? Access Specifiers A.S gives access privileges to outside of application (or) others; they are Public, Protected, Private, Defaults Access Modifiers A.M which gives additional meaning to data, methods and classes, final cannot be modified at any point of time. Same class Same package Subclass Same package non-subclass Different package subclass Different package non-subclass Q) long -2^63 to 2^63 1 Int -2^31 to 2^31 1 Short -2^15 to 2^15 1 Default Values 0L 0 0 Private No No No No No Public Yes Yes Yes Yes Yes Protected Yes Yes Yes Yes No No modifier Yes Yes Yes No NO
Q) Byte code & JIT compiler Byte code is a highly optimized set of instructions. JVM is an interpreter for byte code. Translating a java program into byte code helps makes it much easier to run a program in a wide variety of environment. JIT is a part of JVM, it compiles byte code into executable code in real time, will increase the performance of the interpretations. Q) Diff Access Specifier & Access Modifiers Access Specifier Access Modifiers Q) Wrapper classes Primitive data types can be converted into objects by using wrapper classes. These are java.lang.package. Q) Does Java pass method arguments by value or by reference? A) Java passes all arguments by value, not by reference Q) Arguments & Parameters While defining method, variable passed in the method are called parameters. While using those methods, values passed to those variables are called arguments. Q) Public static void main (String [] args) What if the main method is declared as private? The program compiles properly but at runtime it will give "Main method not public." Message What if the static modifier is removed from the signature of the main method? Program compiles. But at runtime throws an error "NoSuchMethodError". We can write static public void instead of public static void but not public void static. If I do not provide the String array as the argument to the method? Program compiles but throws a runtime error "NoSuchMethodError". If no arguments on the command line, String array of Main method will be empty of null? It is empty. But not null. Variables can have the same name as a method or a class Q) Can an application have multiple classes having main method? A) Yes it is possible. While starting the application we mention the class name to be run. The JVM will look for the Main method only in the class whose name you have mentioned. Hence there is not conflict amongst the multiple classes having main method. Q) Can I have multiple main methods in the same class? A) No the program fails to compile. The compiler says that the main method is already defined in the class. Q) Constructor
Class A( A(){ System.out.println(hello); }} Class B extends A { B(){ System.out.println(friend); }} Class print { Public static void main (String args []){ B b = new B(); } o/p:- Hello friend Q) Diff Constructor & Method Constructor Use to instance of a class No return type Same name as class name This refer to another constructor in the same class Super to invoke the super class constructor Inheritance cannot be inherited We can overload but we cannot overridden Will automatically invoke when an object is created Q) Garbage collection G.C is also called automatic memory management as JVM automatically removes the unused variables/objects (value is null) from the memory. User program cann't directly free the object from memory, instead it is the job of the garbage collector to automatically free the objects that are no longer referenced by a program. Every class inherits finalize () method from java.lang.Object, the finalize () method is called by garbage collector when it determines no more references to the object exists. In Java, it is good idea to explicitly assign null into a variable when no more in use. In Java on calling System.gc () and Runtime.gc (), JVM tries to recycle the unused objects, but there is no guarantee when all the objects will garbage collected. Q) Final, Finally, Finalize Method Grouping java statement Void (or) valid return type As a name except the class method name, begin with lower case. Refers to instance of class Execute an overridden method in the super class Can be inherited Can be inherited Method has called explicitly
Final: - When we declare a sub class a final the compiler will give error as cannot subclass final class Final to prevent inheritance and method overriding. Once to declare a variable as final it cannot occupy memory per instance basis. Final class cannot have static methods Final class cannot have abstract methods Final class can have only a final method. Finally: - Finally create a block of code that will be executed after try catch block has completed. Finally block will execute whether or not an exception is thrown. If an exception is thrown, the finally block will execute even if no catch statement match the exception. Any time a method is about to return to the caller from inside try/catch block, via an uncaught exception or an explicit return statement, the finally clause is also execute. Using System.exit (); in try block will not allow finally code to execute Finalize: - some times an object need to perform some actions when it is going to destroy, if an object holding some non-java resource such as file handle (or) window character font, these resources are freed before the object is going to destroy any cleanup processing before the object is garbage collected. Q) Superclass & Subclass A super class is a class that is inherited whereas subclass is a class that does the inheriting Q) Diff forms of Polymorphism? Method overloading, Method overriding? A) Method overloading, Method overriding through inheritance Q) Method Overloading & Method Overriding? Method Overloading (Compile time polymorphism) Define two or more methods within the same class (or) subclass that share the same name and their parameter declarations are different then the methods are said to be overloaded. Overloaded methods must differ in number of parameters & return type.
Overloaded methods are not required to have the same return type or the list of thrown exceptions. Overloading is particularly used while implementing several methods that implement similar behavior but for
different data types. Method Overriding (Runtime polymorphism) When a method in a subclass has the same name, return type and parameters as the method in the super class then the method in the subclass is override the method in the super class. The access modifier for the overriding method may not be more restrictive than the access modifier of the superclass method
If the super class method is public, the overriding method must be public If the superclass method is protected, the overriding method may be protected or public If the superclass method is package, the overriding method may be packagage, protected, or public If the superclass methods is private, it is not inherited and overriding is not an issue Methods declared as final cannot be overridden.
The throws clause of the overriding method may only include exceptions that can be thrown by the superclass method, including it's subclasses Only member method can be overriden, not member variable class Parent{ int i = 0; void amethod(){
Q) When we use Abstract class? A) Let us take the behaviour of animals, animals are capable of doing different things like flying, digging, Walking. But these are some common operations performed by all animals, but in a different way as well. When an operation is performed in a different way it is a good candidate for an abstract method. Public Abstarctclass Animal{ Public void eat(food food) { } public void sleep(int hours) { } public abstract void makeNoise() } public Dog extends Animal { public void makeNoise() { System.out.println(Bark! Bark); }
Q) Native Methods Native methods are used to call subroutine that is written in a language other than java, this subroutine exist as executable code for the CPU. Q) Cloneable Interface Any class that implements the cloneable interface can be cloned, this interface defines no methods. It is used to indicate that a class allow a bit wise copy of an object to be made.
Q) Clone Generate a duplicate copy of the object on which it is called. Cloning is a dangerous action. Q) Comparable Interface Classes that implements comparable contain objects that can be compared in some meaningful manner. This interface having one method compare () the invoking object with the object. For sorting comparable interface will be used. Ex: - int compareTo (Object obj) Q) Class Encapsulate the run time state of an object (or) interface. You cannot explicitly declare a class object, by using getClass () method you can do that. Class a = x.getClass (); Methods>> getClasses (), getConstructor (), getInterface (), getMethods (), getSuperclass (), getName (). Q) java.lang.Reflect (package) Reflection is the ability of software to analyse it self, to obtain information about the field, constructor, methods & modifier of class. You need this information to build software tools that enables you to work with java beans components. Q) InstanceOf Instanceof means by which your program can obtain run time type information about an object. Ex: - A a = new A (); a instanceof A; Q) java pass arguments by value are by reference? A) by value Q) java lack pointers how do I implements classic pointer structures like linked list? A) using object reference. Q) java.Exe Micro soft provided sdk for java, which includes jexegentool. This converts class file into an .Exec form. Only disadvantage is user needs a M.S java V.M installed. Q) bin & Lib in jdk? bin contains all tools such as javac, appletviewer and awt tool. lib contains API and all packages.
Collections Frame Work Q) Collection classes Abstract collection Abstract List Abstract Set Array List Linked List Hash set Tree Set Hash Map Tree Map Collection Classes Collection Interfaces Collection List Set Sorted Set Map Iterator Legacy classes Dictionary Hash Table Stack Vector Properties Legacy interface Enumerator
Abstract collection Abstract List Abstract Set Array List Array List extends AbstractList and implements the List interface. ArrayList is a variable length of array of object references, ArrayList support dynamic array that grow as needed. A.L allows rapid random access to element but slow for insertion and deletion from the middle of the list. ArrayList is a replacement for Vector. Linked List Extends AbstactSequentialList and implements List interface. L.L provides optimal sequence access, in expensive insertion and deletion from the middle of the list, relatively slow for random access. Methods>> void addFirst (Object obj), addLast (Object obj), Object getFirst (), Object getLast (). Hash Set HashSet extends AbstractSet implements Set interface, it creates a collection that uses HashTable for storage, H.S does not guarantee the order of its elements, if u need storage go for TreeSet Methods>> add (), remove (), size (). Tree Set Extends Abstract Set implements Set interface. Objects are stored in sorted, ascending order. Access and retrial times are quite fast. Hash Map Extends Abstract Map and implements Map interface. H.P does not guarantee the order of elements, so the order in which the elements are added to a H.P is not necessary the order in which they are ready by the iterate. HashMap is similar to Hashtable. Tree Map implements Map interface, a TreeMap provides an efficient means of storing key/value pairs in sorted order and allows rapid retrieval. Collection Interfaces Collection Collection is a group of objects, collection does not allow duplicate elements. Methods>> boolean add (Object obj), boolean addAll (Collection c), Iterator iterator (), boolean remove(Object obj), boolean removeAll(Collection c). List List will extend collection, List stores a sequence of elements that can contain duplicates, elements can be accessed their position in the list using a zero based index. Methods>> void add(int index, Object obj), boolean addAll(int index, Collection c), Object get(int index), int indexOf(Object obj), int lastIndexOf(Object obj), ListIterator iterator(), Object remove(int index). Set Set will extend collection, Set cannot contain duplicate elements. Sorted Set Extends Set to handle Sorted Sets. Methods>> Object last (), Object first (). Map Map maps unique key to value in a map for every key there is a corresponding value and you will lookup the values using keys. Map cannot contain duplicate key and value. In map both the key & value are objects. Methods>> Object get (Object k), Object put (Object k, Object v).
Iterator Before accessing a collection through an iterator you must obtain one if the collection classes provide an iterator () method that returns an iterator to the start of the collection. By using iterator object you can access each element in the collection, one element at a time. Ex: - ArayList arr = new ArrayList (); Arr.add (c); Iterator itr = arr.iterator (); While (itr.hashNext ()) { Object element = itr.next (); } List Iterator List Iterator gives the ability to access the collection, either forward/backward direction Legacy Classes Dictionary is an abstract class that represent key/value storage repository and operates much like Map once the value is stored you can retrieve it by using key. Hash Table HashTable stores key/value pairs in hash table, HashTable is Synchronized when using hash table you have to specify an object that is used as a key, and the value that you want to linked to that key. The key is then hashed, and the resulting hash code is used as the index at which the value is stored with the table. Use H.T to store large amount of data, it will search as fast as vector. Methods>> boolean containsKey(Object key), boolean containsValue(Object value), Object get(Object key), Object put(Object key, Object value) Stack is a sub class of vector, stack includes all the methods defined by vector and adds several of its own. Vector vector holds any type of objects, it is not fixed length and vector is synchronized. We can store primitive data types as well as objects. Default length of vector is up to 10. Methods>> final void addElement(Object element), final int size(), final int capacity(), final boolean removeElementAt(int index), final void removeAllElements(). Properties is a subclass of HashTable, it is used to maintain the list of values in which the key/value is String. Legacy Interfaces Enumeration Define methods by which you can enumerate the elements in a collection of objects. Enumeration is synchronized it having 2 methods hasMoreElements(), nextElement(). Q) Array Array of fixed length of same data type, we can store primitive data types as well as class objects. Arrays are initialized to the default value of their type when they are created, not declared, even if they are local variables Q) Diff Iterator & Enumeration Iterator is not synchronized and enumeration is synchronized. Both are interface, Iterator is collection interface which extends from List interface. Enumeration is a legacy interface, Enumeration having 2 methods Boolean hasMoreElements() & Object NextElement(). Iterator having 3 methods boolean hasNext(), object next(), void remove(). Q) List Iterator It is an interface, List Iterator extends Iterator to allow bi-directional traversal of a list and modification of the elements. Methods are hasNext(), hasPrevious().
Q) Diff HashTable & HashMap Both provide key/value to access the data. The H.T is one of the original collection class in java. H.M is part of new collection frame work. H.T is synchronized and H.M is not. H.M permits null values in it while H.T does not. Iterator in the H.M is fail safe while the enumerator for the H.T is not.
Exception Handling
Object Throwable Error AWT Error Virtual Machine Error Compile time.Ex (checked) OutOfMemory.E StackOverFlow.E EOF.E Runtime Exception (Unchecked) Arithmetic.E NullPointer.E Indexoutof Bound.E Exception
FilenotFound.E
ArrayIndexoutOfBound.E Q) Diff Exception & Error Exception and Error both are subclasses of the Throwable class.
StirngIndexoutOfBound
ExceptionException is generated by java runtime system (or) by manually. An exception is a abnormal condition that transfer program execution from a thrower to catcher. Error Will stop the program execution, Error is a abnormal system condition we cannot handled these. Q) try, catch, throw, throws Try This is used to fix up the error, to prevent the program from automatically terminating, try-catch is used to catching an exception that are thrown by the java runtime system. Throw is used to throw an exception explicitly. Throws A Throws clause list the type of exceptions that a methods might through. Q) Checked & UnChecked Exception :Checked exception is some subclass of Exception. Making an exception checked forces client programmers to deal with the possibility that the exception will be thrown. eg, IOException thrown by java.io.FileInputStream's read() method Unchecked exceptions are RuntimeException and any of its subclasses. Class Error and its subclasses also are unchecked. With an unchecked exception, however, the compiler doesn't force client programmers either to catch the exception or declare it in a throws clause. In fact, client programmers may not even know that the
OutOfMemoryError --> Signals that JVM has run out of memory and that the garbage collector is unable to claim any more free memory. StackOverFlow --> Signals that a stack O.F in the interpreter. ArrayIndexOutOfbound --> For accessing an array element by providing an index values <0 or > or equal to the array size. StringIndexOutOfbound --> For accessing character of a string or string buffer with index values <0 or > or equal to the array size. Arithmetic Exception --> such as divide by zero. ArrayStore Exception --> Assignment to an array element of incompatible types. ClasscastException --> Invalid casting. IllegalArgument Exception --> Illegal argument is used to invoke a method. Nullpointer Exception --> If attempt to made to use a null object. NumberFormat Exception --> Invalid conversition of string to numeric format. ClassNotfound Exception --> class not found. Instantion Exception --> Attempt to create an object of an Abstract class or Interface. NosuchField Exception --> A request field does not exist. NosuchMethod Exception --> A request method does not exist. Q) Can I catch an exception and give my own error message? A) Yes, you can catch servlet errors and give custom error pages for them, but if there are exceptional conditions you can anticipate, it would be better for your application to address these directly and try to avoid them in the first place. If a servlet relies upon system or network resources that may not be available for unexpected reasons, you can use a RequestDispatcher to forward the request to an error page. RequestDispatcher dispatcher = null; request.getRequestDispatcher (/err/SQL.jsp); try { // SQL operation } catch (SQLException se) { dispatcher.forward (request, response); } Web.xml:<error-page> <error-code> HTTP error code <error-code> <exception-type>
java.lang.RuntimeException
</exception-type> <location>
/err/RuntimeException.jsp
All Packages Q) Thread Class Methods: getName() getPriority() isAlive() join() run() Sleep() Start()
Q) Object class All other classes are sub classes of object class; Object class is a super class of all other class. Methods: void notify() void notifyAll() Object Clone() Sting toString() Boolean equals(Object object) Void wait() void finalize() void wait(long milliseconds, int nanoseconds) Q) throwable class Methods: String getMessage() String toString() Q) Javax.servlet Package Interfaces Servlet ServletConfig ServletContext ServletRequest ServletResponse SingleThreadModel Classes GenericServlet ServletInputStream ServletOutputStream Exceptions ServletException UnavaliableException Void printStackTrace() Throwable fillInStackTrace()
GenericServlet (C) public void destroy (); public String getInitParameter(String name); public Enumeration getInitParameterNames(); public ServletConfig getServletConfig(); public ServletContext getServletContext(); public String getServletInfo(); public void init(ServletConfig config) throws ServletException; public void log(String msg); public abstract void service(ServletRequest req, ServletResponse res)
ServletOutputStream (C) public void print (String s) throws IOException; public void println() throws IOException; Servlet (I) public abstract void destroy (); public abstract ServletConfig getServletConfig(); public abstract String getServletInfo(); public abstract void init(ServletConfig config) throws ServletException; public abstract void service(ServletRequest req, ServletResponse res)
ServletConfig (I) public abstract String getInitParameter (String name); public abstract Enumeration getInitParameterNames(); public abstract ServletContext getServletContext(); ServletContext (I) public abstract Object getAttribute (String name); public abstract String getRealPath(String path); public abstract String getServerInfo(); public abstract Servlet getServlet(String name) throws ServletException; public abstract Enumeration getServletNames(); public abstract Enumeration getServlets(); public abstract void log(Exception exception, String msg); ServletRequest (I) public abstract Object getAttribute (String name); public abstract String getParameter(String name); public abstract Enumeration getParameterNames(); public abstract String[] getParameterValues(String name); public abstract String getRealPath(String path); public abstract String getRemoteAddr(); public abstract String getRemoteHost(); public abstract String getServerName(); public abstract int getServerPort(); ServletResponse (I) public abstract String getCharacterEncoding (); public abstract PrintWriter getWriter() throws IOException; public abstract void setContentLength(int len); public abstract void setContentType(String type);
Q) Javax.servlet.Http Package Interfaces HttpServletRequest HttpServletResponse HttpSession HttpSessionContext HttpSessionBindingListener Classes Cookies HttpServlet HttpUtils HttpSessionbindingEvent Exceptions ServletException UnavaliableException
Cookies (C) public Object clone (); public int getMaxAge(); public String getName(); public String getPath(); public String getValue(); public int getVersion(); public void setMaxAge(int expiry); public void setPath(String uri);
HttpSessionbindingEvent (I) public String getName(); public HttpSession getSession(); HttpServletRequest (I) public abstract Cookie[] getCookies(); public abstract String getHeader(String name); public abstract Enumeration getHeaderNames(); public abstract String getQueryString(); public abstract String getRemoteUser(); public abstract String getRequestedSessionId(); public abstract String getRequestURI(); public abstract String getServletPath(); public abstract HttpSession getSession(boolean create); public abstract boolean isRequestedSessionIdFromCookie(); public abstract boolean isRequestedSessionIdFromUrl(); public abstract boolean isRequestedSessionIdValid(); HttpServletResponse (I) public abstract void addCookie(Cookie cookie); public abstract String encodeRedirectUrl(String url); public abstract String encodeUrl(String url); public abstract void sendError(int sc, String msg) throws IOException; public abstract void sendRedirect(String location) throws IOException; public abstract void setHeader(String name, String value); HttpSession (I) public abstract long getCreationTime(); public abstract String getId(); public abstract long getLastAccessedTime(); public abstract HttpSessionContext getSessionContext(); public abstract Object getValue(String name); public abstract String[] getValueNames(); public abstract void invalidate(); public abstract boolean isNew(); public abstract void putValue(String name, Object value); public abstract void removeValue(String name); HttpSessionContext (I) public abstract Enumeration getIds(); public abstract HttpSession getSession(String sessionId); Q) java.sql Package Interfaces Statement PreparedStatement Classes DriverManager Time Exceptions SQL Exception ClassNotFoundException
Q) java.IO Package Interfaces DataInputstream DataOutputstream ObjectInputStream ObjectOutputstream Serializable Externializable Classes BufferInputstream, BufferOutputStream BufferReader, BufferWriter ByteArrayInputStream, ByteArrayOutputstream CharacterarrayReader, CharacterArayWriter DataInputStream, DataOutputStream Filereader, FileWriter ObjectInputStream, ObjectOutputStream Exceptions
SERVLETS Questions Q) Servlet Servlet is server side component, a servlet is small plug gable extension to the server and servlets are used to extend the functionality of the java-enabled server. Servlets are durable objects means that they remain in memory specially instructed to be destroyed. Q) Servlet Life cycle Public void init (ServletConfig config) throws ServletException public void service (ServletRequest req, ServletResponse res) throws ServletException, IOException public void destroy () First the servlet is constructed and then initialized with the init () method, this will call only once. Any request from client is handled initially by the service () method before delegating to the doXxx () methods in the case of HttpServlet. The servlet is removed from service, destroyed with the destroy () method, then garbaged collected and finalized. This will call only once. When your application is stopped (or) Servlet Container shuts down, your Servlet's destroy () method will be called. This allows you to free any resources you may have got hold of in your Servlet's init () method. Q) ServletConfig & ServletContext ServletConfig ServletConfig object is used to obtain configuration data when it is loaded. ServletContext ServletContext is used to obtain information about environment on which a servlet is running.
Q) Where the servlets will be loaded? A) Address space of webserver. Q) Are Servlets multithread? A) Yes, the servlet container allocates a thread for each new request for a single servlet. Each thread of your servlet runs as if a single user were accessing using it alone, but u can use static variable to store and present information that is common to all threads, like a hit counter for instance. Q) What happens to System.out & System.err output in a Servlet? A) System.out goes to 'client side' and is seen in browser, while System.err goes to 'server side' and is visible in error logs and/or on console. Q) Session Tracking Session tracking is the capability of the server to maintain the single client sequential list. Q) Servlet chaining Is a technique in which two are more servlets cooperating in servicing a single client sequential request, where one servlet output is piped to the next servlet output. The are 2 ways (i) Servlet Aliasing (ii) HttpRequest Servlet Aliasing allows you to setup a single alias name for a comma delimited list of servlets. To make a servlet chain opens your browser and give the alias name in URL. HttpRequest construct a URL string and append a comma delimited list of servlets to the end. Q) HttpTunnelling Is a method used to reading and writing serializes objects using a http connection. You are creating a sub protocol inside http protocol that is tunneling inside another protocol. Q) Diff CGI & Servlet Servlet is thread based but CGI is not CGI allow separate process for every client request, CGI is platform dependent and servlet is platform independent. Q) Diff GET & POST GET & POST are used to process request and response of a client. Get method is the part of URL, we send less amount of data through Get. The amount of information limited is 240-255 characters. Using POST we can send large amount of data through hidden fields. Get is to get the posted html data; POST is to post the html data. Q) Diff Http & Generic Servlet HttpServlet class extends Generic servlet, so Generic servlet is parent and HttpServlet is child. Generic is from javax.servlet package, HttpServlet is from javax.servlet.Http package. Http implements all Http protocols, Generic servlet will implements all networking protocol Http is stateless protocol, which means each request is independent of previous one; In generic we cannot maintain the state of next page only main state of current page. A protocol is said to be stateless if it has n memory of prior connection. Http servlet extra functionality is capable of retrieving Http header information. Http servlet can override doGet (), doDelete (), doGet (), doPost (), doTrace (), generic servlet will override Service () method only. Q) The Structure and Deployment of Modern Servlet Web Applications A) /WEB-INF/web.xml /WEB-INF/lib/ [any required jar files] /WEB-INF/classes/ [all class files] WAR-> WARfile can be placed in a servers webapps directory
Q) Servlet mapping? A) <servlet> <servlet-name>watermelon</servlet-name> <servlet-class>myservlets.watermelon</servlet-class> </servlet> <servlet-mapping> <servlet-name>watermelon</servlet-name> <url-pattern>/fruit/summer/*</url-pattern> </servlet-mapping> Q) Timeoutcan be overridden in web.xml? A) <session-config> <session-timeout>e.g.60</session-timeout> </session-config> Q) Init parameter / Define context parameters? <servlet> <servlet-name>HelloWorld2</servlet-name> <servlet-class>examples.servlets.HelloWorld2</servlet-class> <init-param> <param-name>greeting</param-name> <param-value>Welcome</param-value> </init-param> </servlet> Q) Tag Libraries? A) <taglib> <taglib-uri>myTaglib</taglib-uri> <tablig-location>WEB-INF/myTLD.tld</taglib-location> </taglib> Q) How many ways we can instantiate a class.? A) Class.forName().newInstance() and new keyword Q) Client pull & Server push? Client pull Client pull is similar to redirection, with one major difference: the browser actually displays the content from the first page and waits some specified amount of time before retrieving and displaying the content from the next page. It's called client pull because the client is responsible for pulling the content from the next page. Client pull information is sent to the client using the Refresh HTTP header. This header's value specifies the number of seconds to display the page before pulling the next one, and it optionally includes a URL string that specifies the URL from which to pull. If no URL is given, the same URL is used. Here's a call to setHeader() that tells the client to reload this same servlet after showing its current content for three seconds: setHeader("Refresh", "3"); And here's a call that tells the client to display Netscape's home page after the three seconds: setHeader("Refresh", "3; URL=http://home.netscape.com"); Server push server push because the server sends, or pushes, a sequence of response pages to the client.With server push, the socket connection between the client and the server remains open until the last page has been sent. Q) How can a servlet refresh automatically if some new data has entered the database? A) you can use client side refresh are server push Q) Session Tracking techniques (i) URL Rewriting
User Authorization Servers can be set up to restrict access to HTML pages (and servlets). The user is required to enter a user name and password. Once they are verified the client re-sends the authorisation with requests for documents to that site in the http header. Servlets can use the username authorisation sent with request to keep track of user data. For example, a hashtable can be set up to contain all the data for a particular user. When a user makes another request the user name can be used to add new items to their cart using the hashtable. Q) Session Session is a persistence network connection between client and server that facilitate the exchange of information between client and server. A session object created for each user persists on the server side, either until user closes the browser or user remains idle for the session expiration time. 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. HttpSession session = req.getSession(true); //Creating a Session instance session.putValue ("MyIdentifier1", count1); // Storing Value into session Object session.putValue ("MyIdentifier2", count2); session.getValue(MyIdentifier1); // Prints value of Count session.removeValue(MyIdentifier1); // Removing Valuefrom Session Object Q) Cookie advantages & Disadvantages Advantages Persistence offer efficient way to implement session tracking for each client request a cookie can be automatically provide a clients session id. Disadvantage The biggest problem with cookies is that browser do not always accept cookies. Some times browser does not accept cookies. Browser only requires accepting 20 cookies per page and they can limit the cookie size to 4096 bytes. It cannot work if the security level set too high in browser. Cookies are stored in a plain text format so every one can view and modify them. We can put maximum 300 cookies for entire application. Q) Advantages of Sessions over Cookies & URLRewriting? Sessions are more secure and fast because they are stored at server side. But sessions has to be used combindly with cookies (or) URLRewriting for maintaining client id that is session id at client side.
Q) Request Headers User-agent: - Gives the information about client software, browser name, version and information about the machine on which it is running. request.getHeader(user-agent); Q) Why there is no constructor in servlet? A) A servlet is just like an applet in the respect that it has an init() method that acts as a constructor, an initialization code you need to run should e place in the init(), since it get called when the servlet is first loaded. Q) Why do you need both GET & POST methods in servlets? A) A single servlet can be called from different HTML pages, so different method calls can be possible.
Threading Questions
Q) What threads will start when you start the java program? A) Finalizer, Main, Reference Handler, Signal dispatcher. Q) Thread Thread is a smallest unit of dispatchable code. Q) Sleep(), wait(), notify(), notifyAll(), stop(), suspend(), resume() sleep sleep for a thread until some specific amount of time. wait wait for a thread until some specific condition occurs (Or) Tells the calling thread to give up the monitor and go to sleep until some other thread enters the same monitor and calls notify(). 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. stop( ) The thread move to dead state. suspend ( ) & resume( ) To pass and restart the execution of a thread. In case of suspend, thread will be 1suspended by calling the lock on the object. Resume will restart from where it is suspended. join( ) wait for a thread to terminate. Q) yield( ) Yield method temporarily stop the callers thread and put at the end of queue to wait for another turn to be executed. It is used to make other threads of the same priority have the chance to run. -> Thread.sleep(milliseconds); -> Thread.sleep(milliseconds, nanoseconds); Q) Multi Threading Q) Daemon Thread Daemon thread is one which serves another thread, it has no other role normally a daemon thread carry some background program. When daemon thread remains the program exist. Q) Thread Priority MIN_PRIORITY = 1 NORM_PRIORITY = 5 MAX_PRIORITY = 10 Q) Can I restart a stopped thread? A) Once a thread is stopped, it cannot be restarted. Keep in mind though that the use of the stop () method of Thread is deprecated and should be avoided. Q) Thread Priorities Class A implements Runnable{ Thread t; Public clicker(int p){ T = new Thread(this) t.setPriority(p); } public void run(){ } public void stop(){ } public void start(){ t.start(); }
JSP Questions
Directives Page Directive <%@ Page language="java" extends="className" import="className" session="true|false" buffer="8KB" autoFlush="true/false" isThreadSafe="true/false" info="text" errorPage="jspUrl" isErrorPage="true/false" contentType="mimeType %> <%@ include file="relative URL" %> Page directive defines information that will be globally available for that page
Include Directive
Taglib Directive
Include JSP are Servlet at compile time meaning that only once parsed by the compiler, it will act as a C "#include" pulling in the text of the included file and compiling it as if it were part of the including file. We can also include Static files using this directive. Taglib directive enables you to create your own custom tags.
Actions
<Jsp: setProperty>
<Jsp: include>
<Jsp: include page="relativeURL " flush="true" > <Jsp: param name="username" value="jsmith" /> </jsp: include>
Gets the value of a bean property so that you can display it in a result page. It is used to provide other tags with additional information in the form of name, value pairs. This is used to conjunction with jsp:include, jsp:forward, jsp:plugin. Jsp Include includes the JSP are Servlet at request time, it is not parsed by the compiler, and it Includes a static file or sends a request to a dynamic file. When ever the client request will come it will take the request and process the request and the request to be forward to another page and it will also forward the http parameters of the previous page to the destination page. It will work at server side. This action is used to generate client browser specific html tags that ensures the java plug in software is available, followed by execution of applet or java bean component specified in tag.
<Jsp: forward>
<Jsp: forward page="{relativeURL|<%=expression %>}" > <jsp: param name="paramName" value="paramValue"/> </jsp: forward>
<Jsp: plugin>
<Jsp: plugin type="bean/applet" code="classFileName" codebase="classFileDirectoryName" name="instanceName" archive=" align="" height=" " width=" " hspace=" " vspace=" </jsp: plugin>
Q) Implicit Objects Implicit objects request response pageContext session application out Type Subclass of javax.servlet.ServletRequest Subclass of javax.servlet.ServletRespons e javax.servlet.jsp.PageContext javax.servlet.http.HttpSession javax.servlet.ServletContext javax.servlet.jsp.JspWriter Scope Request Page Page Session Application Page Sum useful methods getAttribute, getParameter, getParameterNames, getParameterValues, setAttribute Not typically used by JSP page authors findAttribute, getAttribute, getAttributesScope, getAttributeNamesInScope, setAttribute. getAttribute, getId, setAttribute. getAttribute, getMimeType, getRealPath, setAttribute clear, clearBuffer, flush, getBufferSize,
Q) Declaration A declaration declares one or more variables or methods for use later in the JSP source file. Ex: <%! int a, b, c; %> <%! int accountnumber=2346883; %> <%! String accountname="Thomas"; %> <%! private void processAmount () { ... } %> XML syntax for JSP declaration is <jsp: declaration>int x; </jsp: declaration> Q) Expressions 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. Ex: <%= (new java.util.Date ()).toLocaleString() %> XML syntax for JSP expression is <jsp: expression>Java expression</jsp: expression> Q) Scriptlet A scriptlet can contain 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 2.Write expressions valid in the page scripting language 3.Use any of the JSP implicit objects or any object declared with a <jsp: useBean> tag. 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. XML syntax for JSP scriptlets is <jsp: scriptlet>Java code</jsp: scriptlet> Q) Comments Html comment Creates a comment that is sent to the client in the viewable page source. Ex: <! -- comment [ <%= expression %> ] --> Hidden Comment Documents the JSP file, but is not sent to the client. Ex: <%-- comment --%> Q) MVC
Model: - model is java bean/entity beans that represent the data being transmitted are received. Controller: - Controller is a servlet that performs necessary manipulations to the model.
Internally when jsp is executed by the server it get converted into the servlet so the way jsp & servlet work is almost similar. In jsp we can easily separate the P.L with B.L, but in servlet both are combined. One servlet object is communicated with many numbers of objects, but jsp it is not possible. Q) Can JSP be multi-threaded? How can I implement a thread-safe JSP page? A) By default the service() method of all the JSP execute in a multithreaded fashion. You can make a page thread-safe and have it serve client requests in a single-threaded fashion by setting the page tags is Thread Safe attribute to false: <%@ page is ThreadSafe=false %> Q) How does JSP handle runtime exceptions? A) 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\" %>. Q) How do I prevent the output of my JSP or Servlet pages from being cached by the Web browser? And Proxy server? Web browser caching <%response.setHeader("Cache-Control","no-store"); response.setHeader("Pragma","no-cache"); response.setDateHeader ("Expires", 0); %> Proxy server caching response.setHeader("Cache-Control","private"); Q) What's a better approach for enabling thread-safe servlets & JSPs? SingleThreadModel Interface or Synchronization? A) SingleThreadModel technique is easy to use, and works well for low volume sites. If your users to increase in the future, you may be better off implementing explicit synchronization for your shared data 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 exhausts the servlet instance pool. In that case, all the unserviced requests are queued until something becomes free. Q) Servlet to- JSP communicate? public void doPost(HttpServletRequest req, HttpServletResponse res) { Try{ govi.FormBean f = new govi.formBean(); string id = req.getParameter(id); f.setName(req.getParameter(name)); f.setName(req.getParameter(addr)); f.setPersonalizationInfo(info); req.setAttribute(fBean,f); getServletConfig().getServletContext().getRequestDispatcher(/jsp/Bean1.jsp).forward(req, res); } catch(Exception ex); } } The jsp page Bean1.jsp can then process fBean,
<jsp:useBean id=fBean class=govi.formBean scope=request /> <jsp:getProprety name=fBean property=name /> <jsp:getProprety name=fBean property=addr /> Q) JSP- to-EJB Session Bean communicate? <%@ page import="javax.naming.*, javax.rmi.PortableRemoteObject, foo.AccountHome, foo.Account" %> <%! AccountHome accHome=null; public void jspInit() { InitialContext cntxt = new InitialContext( ); Object ref= cntxt.lookup("java:comp/env/ejb/AccountEJB"); accHome = (AccountHome)PortableRemoteObject.narrow(ref,AccountHome.class); } %> <% Account acct = accHome.create(); acct.doWhatever(...); %> Q) Servlet output - to - another Servlet? Servlet1 ServletContext sc = getServletContext(); RequestDispatcher rd = sc.getRequestDispatcher(/../srevlet2) ; rd.forward(req, res); Servlet2 Public void service(servletRequest req, servletResponse res) { ServletContext sc = getServletContext(); RequestDispatcher rd = sc.getRequestDispatcher(/../srevlet1) ; rd.include(req, res); } Q) How do you pass an InitParameter to a JSP? <%! 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); } } %> Q) How to view an image stored on database with JSP? <%@ page language="java" import="java.sql.*,java.util.*"%> <% String image_id = (String) request.getParameter("ID"); if (image_id != null){ try { Class.forName("interbase.interclient.Driver");
Two
Two
Q) Does the JDBC-ODBC Bridge support multiple concurrent open statements per connection? A) No. You can open only one Statement object per connection when you are using the JDBC-ODBC Bridge.
A) getASSCIISteram() read values which are character in nature. GetBinaryStream() used to read images.
Q) ResultSetMetaData It is used to find out the information of a table in a data base. ResultSet rs = stmt.executeQuery("SELECT * FROM "+ table); ResultSetMetaData rsmd = rs.getMetaData(); Methods in ResultSetMetaData getColumnCount(), getColumnName(), getColumnLabel(), getColumnType(), getTableName(), Q) Database MetaData You need some information about the data base & dictionary we use this .To find out tables, stored procedure names, columns in a table, primary key of a table we use this, this is the largest interface in java.sql package Connection con = DriverManager.getConnection(jdbcURL, "", "");
EJB Questions Q) Application server & Web server Application server is a generalized server for running more than one application like ejb, rmi, jsp, servlets. webserver is for request, response paradigm. It takes the client request and send response back to the client and the connection is closed. A.S cannot process Http request, but takes the forwarded request from W.S and process the business logic and send the output to the W.S which it turns send to the client. A.S manage transactions, security, persistence and lot more, but W.S cannot help in this regards. W.S takes only the Http request. A.S provides runtime environment for server side components, they provide middleware services such as resource pooling and network. Q) Diff Bean & Ejb Q) SessionBeans Session beans are not persistence there are short lived beans. S.B can perform database operations but S.B it self is not a persistence objects. S.B are business process objects they implements business logic, business rules and workflow. Statefull Session Bean & Stateless Session Bean Statefull session bean is a bean that is designed to service business process that span multiple methods request/transaction, S.S.B can retain their state on the behalf of individual client. All S.S.B can exposes only a single ejbCreate() method it does not take any parameters. Stateless session bean these are single request business process is one that does not require state to be maintained across method invocation. S.S.B cannot hold the state. Statefull session bean do not have pooling concept Stateless session bean instance can be pooled. If the business process span multiple invocations there by requiring a conversational then S.S.B will be ideal choice. If the business last only for a single method call, S.S.B are suitable. Q) Entity Bean Entity beans are permanent business entities because their state is saved in permanent data storage. E.B are persistence objects, E.B contain data related logic. E.B are permanent so if any machine crashes, the E.B can be reconstructed in memory again by simple reading the data back in from the database. Bean managed Persistence & Container managed Persistence B.P is an entity bean that must be persisted by hand, other words component developer must write the code to translate your in-memory fields into an underlying data store. You handle these persist operations your self, you place your data base calls in ejbLoad() and ejbStore(). Finder methods only for B.M.P for C.M.P your ejb container will implement the finder methods. In this commit, rollback, begin are transactions In B.M.P findByPK() return a reference to the actual bean object. You do not have to do anything to synchronize with data base. In entity bean deployment descriptor you specify which fields that the container should manage. The transaction in C.M.P are TX-Support, TX-NotSupport, TX-require. He findByPK() in C.M.P return void because the method is internally implemented. Q) Message Driven Bean M.D.B process messages asynchronously are deliver via JMS. M.D.Bs are stateless, server side, transaction aware components used for asynchronous JMS messages. It acts as a JMS message listener which JMS
Q) When to use container managed and bean managed persistence? Container managed persistance is used when the persistant data store is a relational database and there is one to one mapping between a data represented in a table in the relational database and the ejb object. Bean managed persistance in used when there is no one to one mapping of the table and a complex query reteriving data from several tables needs to be performed to construct an ejb object. Bean managed is also used when the persistence data storage is not a relational database. Q) When to choose Statefull & Stateless Session bean? A) Does the business process span multiple method invocations, requiring a conversational state if so the state full model fits very nicely. If your business process last for a single method call the stateless paradigm will better suite needed. Q) Diff Statefull Session & Entity Bean Both S.S.B & E.B undergo passivation and activation. The E.B have a separate ejbStore() callback for saving state during passivation & a separate ejbLoad() callback for loading state during activation. We do not need these callbacks for S.S.B because the container is simply uses object serialization to persist S.S.B fields. Q) Object-Relational Mapping Mapping of objects to relational database is a technology called O.R.M. O.R.M is a persistence mechanism of persistence objects than simple object serialization. Q) When to use which bean Session Bean & Entity Bean? E.B are effective when application want to access one row at a time, if many rows needed to be fetched using session bean can be better alternative. E.B are effective when working with one row at a time cause of lot of N.W traffic. S.B are efficient when client wants to access database directly, fetching, updating multiple rows from data base. S.B for application logic. Q) Deployment Descriptor D.D contains information for all the beans in the ejb.jar file. D.D enables ejb container to provide implicit services to enterprise bean components, these services can gain your bean with out coding. D.D is a XML file. Q) ejbCreate() In stateless session bean can have only one ejbCreate() method it must take no arguments. Remember that ejbCreate() is essentially analogous to a constructor for ejb; it initializes an instance internal state variable. Because the stateless session bean has no client specific variables. Q) Can a Session Bean be defined without ejbCreate() method? A) The ejbCreate() methods is part of the bean's lifecycle, so, the compiler will not return an error because there is no ejbCreate() method. - The home interface of a Stateless Session Bean must have a single create() method with no arguments, while the session bean class must contain exactly one ejbCreate() method, also without arguments. - Stateful Session Beans can have arguments (more than one create method) - Stateful beans can contain multiple ejbCreate() as long as they match with the home interface definition Q) Can i call remove() on a Stateless Session bean? A) Yes, The life of a Stateless Session bean for a client is just till the execution of the method that the client would have called on the beanafter the execution of that method if the client calls another method, then a different
Q) Conversational & Non-conversational Conversational is an interaction between the bean and client, stateless session bean is a bean that do not hold multi method conversation with clients. Stateless.S.B cannot hold state, Statefull.S.B can hold conversational with client that may span multiple method request. Q) JNDI to locate Home Objects H.O are physically located some where on the N.W, perhaps in the address space of the Ejb Container. For client to locate H.O, you must provide nick name for your beans H.O. Client will use this nick name to identify the H.O it wants, we will specify the nice name in the Deployment descriptor. Container will use this nick name, JNDI goes over the N.W to some directory service to look for the H.O. Properties props = System.getProperties(); Context ctx = new InitialContext(props); MyHome home = (MyHome)ctx.lookup(MyHome); MyRemoteInterface remote = home.create(); Q) Diff servlet/jsp session & EJB session logical point of view a servlet/jsp session is similar to an ejb session. A session in servlet is maintained by the servlet container through Http session object.. That is acquiring through the request object. You cannot instantiate Http session object. A session in Ejb is maintained using S.B, you design bean that can maintain business logic. You can have 2 types of beans 1. Stateless 2. Stateful. Q) ejbCretae( ) & ejbPostCreate( ) ejbCreate() is called just before the state of the bean is written to the persistence storage. After this method is completed a new record is created and written. ejbPostCreate() is called after the bean has been written to the database and the bean data has been assigned to an Ejb object. Q) Can map Entity bean to more than one table? A) Q) EAR, WAR, JAR All EJB classes should package in a JAR file, All web components pages, servlets, gif, html, applets, beans, ejb modules, classes should be packaged into WAR file. EAR file contain all the JAR & WAR files. Note that each JAR, WAR, EAR file will contain D.D Q) Life cycle Life cycle of a Stateful Session Bean
Stateful session bean has 3 states Does Not Exist, Method Ready Pool and Passivated states. A bean has not yet instantiated when it is in the Does Not Exist Sate. Once a container creates one are more instance of a Stateful Session bean it sets them in a Method Ready State. In this state it can serve requests from its clients. Like Stateless beans, a new instance is created(Class.newInstance()), the context is passed (setSessionContext()) and finally the bean is created with the ejbCreate().
ejbPassivate( ) If too many beans are instantiated, the container can passivate some of them .ie write the bean to some temp storage. The container should release all resources held by the bean. Just before passivating, the container calls the ejbPassivate() method. So release all resources here,ie,close socket connections..etc. ejbActivate( ) When a passiavted bean is called, its said to be activated. The container then calls the ejbActivate() method. Acquire all the required resources for the bean in this method. ie get socket connection
A S.S.B has only two states: Does Not Exist and Method Ready Pool. A bean has not yet instantiated when it is in the Does Not Exist Sate. When the EJB container needs one are more beans, it creates and set then in the Method Ready Pool Sate. This happens through the creation of a new instance(Class.newInstance()), then it is set its context (setSessionContext()) and finally calls the ejbCreate() method. The ejbRemove() method is called to move a bean from the Method Ready Pool back to Does Not Exist State.
Q) Deployment descriptor of EJB <?xml version="1.0"?> <!DOCTYPE ejb-jar PUBLIC "-//Sun Microsystems, Inc.//DTD Enterprise JavaBeans 1.1//EN" "http://java.sun.com/j2ee/dtds/ejb-jar_1_1.dtd"> <ejb-jar> <description> This Deployment includes all the beans needed to make a reservation: TravelAgent, ProcessPayment, Reservation, Customer, Cruise, and Cabin. </description> <enterprise-beans> <session> <ejb-name>TravelAgentBean</ejb-name> <remote>com.titan.travelagent.TravelAgent</remote> ... </session> <entity> <ejb-name>CustomerBean</ejb-name> <remote>com.titan.customer.Customer</remote> ... </entity> <session> <ejb-name>ProcessPaymentBean</ejb-name> <remote>com.titan.processpayment.ProcessPayment</remote> ... </session> ... </enterprise-beans> <assembly-descriptor> ... </assembly-descriptor> ... </ejb-jar> Q) Remote Interface public interface Hello extends javax.ejb.EJBObject { public String hello() throws java.rmi.RemoteException; } Home Interface
public interface HelloHome extends javax.ejb.EJBHome { Hello create() throws java.rmi.RemoteException; javax.ejb.CreateException; } Bean Class public class HelloBean implements javax.ejb.SessionBean { private SessionContex ctx; public void ejbCreate(); public abstract void ejbRemove(); public abstract void ejbActivate(); public abstract void ejbPassivate(); public abstract void setSessionContext(SessionyContext ctx); public String hello(){ System.out.println(hello()); Return hello world; } Client public class HelloClient { public static void main(String args[ ]) properties props = system.getProperties(); Context ctx = new InitialContext(props); Object obj = ctx.lookup(HelloHome); HelloHome home = (HelloHome) javax.rmi.protableRemoteObject.narrow(obj, HelloHome.class); Hello hello = home.create(); System.out.println(hello.hello()); Hello.remove(); } Q) Transaction Isolation levels TRANSACTION_READ_UNCOMMITTED The transaction can read uncommitted data. Dirty reads, nonrepeatable reads, and phantom reads can occur. Bean methods with this isolation level can read uncommitted change. TRANSACTION_READ_COMMITTED The transaction cannot read uncommitted data; data that is being changed by a different transaction cannot be read. Dirty-reads are prevented; nonrepeatable reads and phantom reads can occur. Bean methods with this isolation level cannot read uncommitted data. TRANSACTION_REPEATABLE_READ The transaction cannot change data that is being read by a different transaction. Dirty reads and nonrepeatable reads are prevented; phantom reads can occur. Bean methods with this isolation level have the same restrictions as Read Committed and can only execute repeatable reads. TRANSACTION_SERIALIZABLE The transaction has exclusive read and update privileges to data; different transactions can neither read nor write the same data. Dirty reads, nonrepeatable reads, and phantom reads are prevented. This isolation level is the most restrictive.
Q) ACID Properties When you properly use transaction your operations will execute ACID properties. (i) Atomicity Guarantees that many operations are bundled together and appears as one contiguous unit of work. Ex:- When you transfer money from one bank account to another you want to add funds to one account and remove funds from the other transaction and you want both operations to occur or neither to occur. (ii) Consistency Guarantees that a transaction will leave the system state to be consistent after a transaction completes. Ex:- A bank system state could be consist if the rule bank account balance must always be +ve. (iii) Isolation Protect concurrently executing transaction from seeing each other incomplete results. Ex:- If you write a bank account data to a database, the transaction may obtain locks on the bank account record (or) table. The lock guarantee that no other updates can interfere. (iv) Durability Resources keep a transactional log for resources crashes, the permanent data can be reconstructed by reapplying the steps in the log. Q) Diff Sax & DOM DOM SAX
Q) Hot deployment Hot Deployment in Web Logic is he act of deploying, re-deploying and un-deploying EJBs while the server is still running. Q) When should I use TxDataSource instead of Datasource? If your application (or) environment meet the following criteria you should use - uses JTA - uses EJB container in web logic server to manage transactions. - Includes multiple database updates with single transaction. - Access multiple resources, such as database & JMS during transactions. - Use same connection pool on multiple servers. Q) Clustering In J2ee container can be distributed, a distributed container consist of number of JVMs running on one are more host machines. In this setup, application components can be deployed on a number of JVMs. Subject to the type of loading strategy and the type of the component the container can distributed the load of incoming request to one of these JVMs.
Struts Questions
Q) Diff Struts1.0 & 1.1? A) 1.RequestProcessor class, 2.Method perform() replaced by execute() in Struts base Action Class 3. Changes to web.xml and struts-config.xml, 4. Declarative exception handling, 5.Dynamic ActionForms, 6.Plugins, 7.Multiple Application Modules, 8.Nested Tags, 9.The Struts Validator Change to the ORO package, 10.Change to Commons logging, 11. Removal of Admin actions, 12.Deprecation of the GenericDataSource Q) Struts Validator Framework? A) Struts Framework provides the functionality to validate the form data. It can be use to validate the data on the users browser as well as on the server side. Struts Framework emits the java scripts and it can be used validate the form data on the client browser Q) ActionServlet:The class org.apache.struts.action.ActionServlet is the called the ActionServlet. In the Jakarta Struts Framework this class plays the role of controller. All the requests to the server goes through the controller. Controller is responsible for handling all the requests. Q) Action Class:The Action Class is part of the Model and is a wrapper around the business logic. The purpose of Action Class is to translate the HttpServletRequest to the business logic. To use the Action, we need to Subclass and overwrite the execute() method. In the Action Class all the database/business processing are done. It is advisable to perform all the database related stuffs in the Action Class. The ActionServlet (commad) passes the parameterized class to Action Form using the execute() method. The return type of the execute method is
The solution for the redundant and expensive JNDI lookup process problem is to cache those service objects when the client performs JNDI lookup first time and reuse that service object from the cache second time onwards for other clients. This technique maintains a cache of service objects and looks up the JNDI only first time for a service object. This technique reduces redundant and expensive JNDI lookup process thus increasing
Here the clients call ServiceLocator class to get a service object rather than calling JNDI directly. ServiceLocator acts as interceptor between client and JNDI. For source code and different flavors of implementation of this Pattern, see the following links. Session Facade EJB clients (swing, servlets, jsps etc) can access entity beans directly. If EJB clients access entity beans directly over the network, it takes more network calls and imposes network overhead.
Here the servlet calls multiple entity beans directly to accomplish a business process, thereby increasing the number of network calls. The solution for avoiding number of network calls due to directly accessing multiple entity beans is to wrap entity beans with session bean (Facade). The EJB client accesses session bean (Facade) instead of entity beans through coarse grained method call to accomplish a business process.
The client has to wait till all the eight synchronous steps complete. This synchronous execution takes a long time and has an impact on performance when the method process is huge. To avoid blocking of a client, use asynchronous message driven beans, so that client does not have to wait for a return value. If a client uses asynchronous messaging then the client need not wait for a return value but can continue its flow of execution after sending the message.
Value Object When a client calls a remote method there will be process of marshalling, network calls and unmarshalling involved for the remote method invocation. If you choose fine grained approach when calling methods remotely, there will be a significant network overhead involved. For example if you call fine grained method like this, remoteObject.getName(); remoteObject.getCity(); remoteObject.getState(); remoteObject.getZipCode(); Here, there are four network calls from client to the remote object because every method call is remote method call.
The solution for avoiding many network calls due to fine grained method calls is to use coarse grained approach. For example : // create an Value Object and fill that object locally PersonInfo person = new PersonInfo(); person.setName("Ravi"); person.setCity("Austin"); person.setState("TX"); person.zipCode("78749"); // send Value Object through network remoteObject.getPersonInfo(person); Here, there is only one network call instead of three network calls and PersonInfo object is a Value Object. The following figure illustrates the coarse grained approach that is passing a Value Object through network.
Value Object is an object that is passed over the network rather than passing each attributes separately thus increasing performance by reducing network calls. ValueObjectFactory For a single request, a client might need to access multiple server side components such as different session beans and entity beans. In such situations the client accesses multiple components over the network, this increases the network traffic and has an impact on the performance.
To reduce the network traffic due to accessing multiple components by a client for a single request, let ValueObjectFactory hold different ValueObjects as place holders and respond with a single ValueObject for a client request. Here ValueObjectFactory holds creation and delegation logic of ValueObjects for different client requests.
Value List Handler J2EE applications generally have the search facility and have to search huge data and retrieve results. If an application returns huge queried data to the client, the client takes long time to retrieve that large data and If that application uses entity bean to search data, it has an impact on.
1. Use Data Access Objects (DAO) rather than Entity beans 2. Return small quantity of data multiple times iteratively rather than returning large amount of data at once to the client. Data Access Object encapsulates JDBC access logic. ValueListHandler caches list of Value objects that are retrieved through DAO. When client wants to search data, It calls ValueListHandler that is in turn responsible for
Singleton There will be only one instance for the entire JVM. You can achieve this by having the private constructor in the class. Singleton is probably the most widely used design pattern. Its intent is to ensure that a class has only one instance, and to provide a global point of access to it. There are many situations in which a singleton object is necessary: a GUI application must have a single mouse, an active modem needs one and only one telephone line, an operating system can only have one window manager, and a PC is connected to a single keyboard Public class Singleton{ Private static final Singleton s = new Singleton(); Private Singleton(){} Public static Singleton getInstance(){ return s;} } Business Delegate The Business Delegate hides the underlying implementation details of the business service, such as lookup & access details of the EJB architecture. The business delegates acts as a client-side business abstraction and hides the implementation of the business services. The delegate may cache results and references to remote business services. Caching can significantly improve performance, because it limits unnecessary and potentially costly round trips over the network. A Business Delegate uses a component called the Lookup Service. The Lookup Service is responsible for hiding the underlying implementation details of the business service lookup code. The Lookup Service may be written as part of the Delegate, but we recommend that it be implemented as a separate component, as outlined in the Service Locator pattern Figure shows the class diagram representing the Business Delegate pattern. The client requests the BusinessDelegate to provide access to the underlying business service. The BusinessDelegate uses a LookupService to locate the required BusinessService component.
Security Questions Q) Java Security Model Byte code verifier Which examine the byte code of a class before executing. The verifier checks that the instructions cannot perform actions that are obviously damaging. ClassLoader ClassLoader, which restrict access to the classes which can be loaded into JVM, ClassLoader keeps the record of classes which can be loaded into JVM.
Security manager
Restrict access to potentially dangerous operations. S.M provides a sand box in which applet run. You can also define a set of sand boxes, applying a different san box to each program. S.M is a class that controls weather a specific operation are permitted, S.M will perform operations like opening N.W socket, creating S.M, perform N.W multi cast etc Q) Basic Authentication & Digest Authentication Basic Authentication Is a security model in this the client must authenticate itself with user id and password for each resource to access. In this the user id and password are sent by the client in base-64 encoded string, the server decode the string and looks in the data base for match. If it finds a match grant access to the requested resource. Digest Authentication In this the user id and password does not send across the network instead send a digest representation of password.
Database Questions Q) DML insert, update, delete DDL create, alter, drop, truncate, rename.
DQL select DCL grant, revoke. TCL commit, rollback, savepoint. Q) Normalization Normalization is the process of simplifying the relationship between data elements in a record. Q) Normal forms (i) 1st normal form : - 1st N.F is achieved when all repeating groups are removed, and P.K should be defined. (ii) 2nd normal form : - Eliminate any non full dependence of data item on record keys. (iii) 3rd normal form : - Eliminate any transitive dependence of data items on P.Ks. Q) Diff Primary key and a Unique key? What is foreign key? A) Both primary key and unique enforce uniqueness of the column on which they are defined. But by default primary key creates a clustered index on the column, where are unique creates a nonclustered index by default. Another major difference is that, primary key doesn't allow NULLs, but unique key allows one NULL only. Foreign key constraint prevents any actions that would destroy link between tables with the corresponding data values. A foreign key in one table points to a primary key in another table. Foreign keys prevent actions that would leave rows with foreign key values when there are no primary keys with that value. The foreign key constraints are used to enforce referential integrity. CHECK constraint is used to limit the values that can be placed in a column. The check constraints are used to enforce domain integrity. NOT NULL constraint enforces that the column will not accept null values. The not null constraints are used to enforce domain integrity, as the check constraints. Q) Diff Delete & Truncate? A) Rollback is possible after DELETE but TRUNCATE remove the table permanently and cant rollback. Truncate will remove the data permanently we cannot rollback the deleted data. Dropping : (Table structure + Data are deleted), Invalidates the dependent objects, Drops the indexes Truncating : (Data alone deleted), Performs an automatic commit, Faster than delete Delete : (Data alone deleted), Doesnt perform automatic commit Q) Diff Varchar and Varchar2? A) 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. Q) Diff LONG & LONG RAW? A) You use the LONG datatype to store variable-length character strings. The LONG datatype is like the VARCHAR2 datatype, except that the maximum length of a LONG value is 32760 bytes. You use the LONG RAW datatype to store binary data (or) byte strings. LONG RAW data is like LONG data, except that LONG RAW data is not interpreted by PL/SQL. The maximum length of a LONG RAW value is 32760 bytes. Q) Diff Function & Procedure Function is a self contained program segment, function will return a value but procedure not. Procedure is sub program will perform some specific actions. Q) How to find out duplicate rows & delete duplicate rows in a table? A)
Example: Create public synonym suppliers for app. suppliers; Example demonstrates how to create a synonym called suppliers. Now, users of other schemas can reference the table called suppliers without having to prefix the table name with the schema named app. For example: Select * from suppliers;
If this synonym already existed and you wanted to redefine it, you could always use the or replace phrase as follows: Create or replace public synonym suppliers for app. suppliers; Dropping a synonym It is also possible to drop a synonym. drop [public] synonym [schema .] synonym_name [force]; public -- phrase allows you to drop a public synonym. If you have specified public, then you don't specify a schema. Force -- phrase will force Oracle to drop the synonym even if it has dependencies. It is probably not a good idea to use the force phrase as it can cause invalidation of Oracle objects. example: Drop public synonym suppliers; This drop statement would drop the synonym called suppliers that we defined earlier. Q) What is an alias and how does it differ from a synonym? A) An alias is an alternative to a synonym, designed for a distributed environment to avoid having to use the location qualifier of a table or view. The alias is not dropped when the table is dropped. Q) What are joins? Inner join & outer join? A) By using joins, you can retrieve data from two or more tables based on logical relationships between the tables Inner Join: - returns all rows from both tables where there is a match Outer Join: - outer join includes rows from tables when there are no matching values in the tables. LEFT JOIN or LEFT OUTER JOIN The result set of a left outer join includes all the rows from the left table specified in the LEFT OUTER clause, not just the ones in which the joined columns match. When a row in the left table has no matching rows in the right table, the associated result set row contains null values for all select list columns coming from the right table. RIGHT JOIN or RIGHT OUTER JOIN. A right outer join is the reverse of a left outer join. All rows from the right table are returned. Null values are returned for the left table any time a right table row has no matching row in the left table. FULL JOIN or FULL OUTER JOIN. A full outer join returns all rows in both the left and right tables. Any time a row has no match in the other table, the select list columns from the other table contain null values. When there is a match between the tables, the entire result set row contains data values from the base tables. Q. Diff join and a Union? A) A join selects columns from 2 or more tables. A union selects rows. when using the UNION command all selected columns need to be of the same data type. The UNION command eliminate duplicate values. Q. Union & Union All? A) The UNION ALL command is equal to the UNION command, except that UNION ALL selects all values. It cannot eliminate duplicate values. > SELECT E_Name FROM Employees_Norway UNION ALL SELECT E_Name FROM Employees_USA Q) Is the foreign key is unique in the primary table? A) Not necessary Q) Table mentioned below named employee ID NAME MID 1 CEO Null 2 VP CEO
Asked to write a query to obtain the following output CEO Null VP CEO Director VP A) SQL> Select a.name, b.name from employee a, employee b where a.mid=b.id(+). Q) Explain a scenario when you dont go for normalization? A) If we r sure that there wont be much data redundancy then dont go for normalization. Q) What is Referential integrity? A) R.I refers to the consistency that must be maintained between primary and foreign keys, i.e. every foreign key value must have a corresponding primary key value. Q) What is Normalization? Explain in details? A) Normalization is the process of simplifying the relation ship between data elements in a record. 1st N.F -- the big table is broken into many small tables, such that each table has a primary key. 2nd N.F Removes partial dependency. Ie The columns in a table which is not completely dependant on the primary key are taken to a separate table 3rd N.F Removes Transitive dependency. Ie If X is the primary key in a table. Y & Z are columns in the same table. Suppose Z depends only on Y and Y depends on X. Then Z does not depend directly on primary key. So remove Z from the table to a look up table. Q) What techniques are used to retrieve data from more than one table in a single SQL statement? A) Joins, unions and nested selects are used to retrieve data. Q) What is a view? Why use it? A) A view is a virtual table made up of data from base tables and other views, but not stored separately. Q) SELECT statement syntax? A) SELECT [ DISTINCT | ALL ] column_expression1, column_expression2, .... [ FROM from_clause ] [ WHERE where_expression ] [ GROUP BY expression1, expression2, .... ] [ HAVING having_expression ] [ ORDER BY order_column_expr1, order_column_expr2, .... ] column_expression ::= expression [ AS ] [ column_alias ] from_clause ::= select_table1, select_table2, ... from_clause ::= select_table1 LEFT [OUTER] JOIN select_table2 ON expr ... from_clause ::= select_table1 RIGHT [OUTER] JOIN select_table2 ON expr ... from_clause ::= select_table1 [INNER] JOIN select_table2 ... select_table ::= table_name [ AS ] [ table_alias ] select_table ::= ( sub_select_statement ) [ AS ] [ table_alias ] order_column_expr ::= expression [ ASC | DESC ] Q) DISTINCT clause? A) The DISTINCT clause allows you to remove duplicates from the result set. > SELECT DISTINCT city FROM supplier; Q) COUNT function? A) The COUNT function returns the number of rows in a query > SELECT COUNT (*) as "No of emps FROM employees WHERE salary > 25000;
Q) What are some sql Aggregates and other Built-in functions? A) AVG, SUM, MIN, MAX, COUNT and DISTINCT.