Java Interview

Share Embed Donate


Short Description

Imp questions of Java Interview...

Description

Junior Java programmer interview questions 1. What is the purpose of finalization? - The purpose of finalization is to give an unreachable object the opportunity to perform any cleanup processing before the object is garbage collected. 2. What is the difference between the Boolean & operator and the && operator? - If an expression involving the Boolean & operator is evaluated, both operands are evaluated. Then the & operator is applied to the operand. When an expression involving the && operator is evaluated, the first operand is evaluated. If the first operand returns a value of true then the second operand is evaluated. The && operator is then applied to the first and second operands. If the first operand evaluates to false, the evaluation of the second operand is skipped. 3. How many times may an object’s finalize() method be invoked by the garbage collector? - An object’s finalize() method may only be invoked once by the garbage collector. 4. What is the purpose of the finally clause of a try-catch-finally statement? The finally clause is used to provide the capability to execute code no matter whether or not an exception is thrown or caught. 5. What is the argument type of a program’s main() method? - A program’s main() method takes an argument of the String[] type. 6. Which Java operator is right associative? - The = operator is right associative. 7. Can a double value be cast to a byte? - Yes, a double value can be cast to a byte. 8. What is the difference between a break statement and a continue statement? - A break statement results in the termination of the statement to which it applies (switch, for, do, or while). A continue statement is used to end the current loop iteration and return control to the loop statement. 9. What must a class do to implement an interface? - It must provide all of the methods in the interface and identify the interface in its implements clause. 10. What is the advantage of the event-delegation model over the earlier eventinheritance model? - The event-delegation model has two advantages over the event-inheritance model. First, it enables event handling to be handled by objects other than the ones that generate the events (or their containers). This allows a clean separation between a component’s design and its use. The other advantage of the event-delegation model is that it performs much better in applications where many events are generated. This performance improvement is due to the fact that the event-delegation model does not have to repeatedly process unhandled events, as is the case of the event-inheritance model. 11. How are commas used in the intialization and iteration parts of a for statement? - Commas are used to separate multiple statements within the initialization and iteration parts of a for statement. 12. What is an abstract method? - An abstract method is a method whose implementation is deferred to a subclass. 13. What value does read() return when it has reached the end of a file? - The read() method returns -1 when it has reached the end of a file. 14. Can a Byte object be cast to a double value? - No, an object cannot be cast to a primitive value.

15. What is the difference between a static and a non-static inner class? - A nonstatic inner class may have object instances that are associated with instances of the class’s outer class. A static inner class does not have any object instances. 16. If a variable is declared as private, where may the variable be accessed? - A private variable may only be accessed within the class in which it is declared. 17. What is an object’s lock and which object’s have locks? - An object’s lock is a mechanism that is used by multiple threads to obtain synchronized access to the object. A thread may execute a synchronized method of an object only after it has acquired the object’s lock. All objects and classes have locks. A class’s lock is acquired on the class’s Class object. 18. What is the % operator? - It is referred to as the modulo or remainder operator. It returns the remainder of dividing the first operand by the second operand. 19. When can an object reference be cast to an interface reference? - An object reference be cast to an interface reference when the object implements the referenced interface. 20. Which class is extended by all other classes? - The Object class is extended by all other classes. 21. Can an object be garbage collected while it is still reachable? - A reachable object cannot be garbage collected. Only unreachable objects may be garbage collected. 22. Is the ternary operator written x : y ? z or x ? y : z ? - It is written x ? y : z. 23. How is rounding performed under integer division? - The fractional part of the result is truncated. This is known as rounding toward zero. 24. What is the difference between the Reader/Writer class hierarchy and the InputStream/OutputStream class hierarchy? - The Reader/Writer class hierarchy is character-oriented, and the InputStream/OutputStream class hierarchy is byte-oriented. 25. What classes of exceptions may be caught by a catch clause? - A catch clause can catch any exception that may be assigned to the Throwable type. This includes the Error and Exception types. 26. If a class is declared without any access modifiers, where may the class be accessed? - A class that is declared without any access modifiers is said to have package access. This means that the class can only be accessed by other classes and interfaces that are defined within the same package. 27. Does a class inherit the constructors of its superclass? - A class does not inherit constructors from any of its superclasses. 28. What is the purpose of the System class? - The purpose of the System class is to provide access to system resources. 29. Name the eight primitive Java types. - The eight primitive types are byte, char, short, int, long, float, double, and boolean. 30. Which class should you use to obtain design information about an object? The Class class is used to obtain information about an object’s design.

Java interview questions 1. Can there be an abstract class with no abstract methods in it? - Yes

2. Can an Interface be final? - No 3. Can an Interface have an inner class? - Yes. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15. 16. 17. 18. 19.

public interface abc { static int i=0; void dd(); class a1 { a1() { int j; System.out.println("inside"); }; public static void main(String a1[]) { System.out.println("in interfia"); } } }

20. Can we define private and protected modifiers for variables in interfaces? No 21. What is Externalizable? - Externalizable is an Interface that extends Serializable Interface. And sends data into Streams in Compressed Format. It has two methods, writeExternal(ObjectOuput out) and readExternal(ObjectInput in) 22. What modifiers are allowed for methods in an Interface? - Only public and abstract modifiers are allowed for methods in interfaces. 23. What is a local, member and a class variable? - Variables declared within a method are “local” variables. Variables declared within the class i.e not within any methods are “member” variables (global variables). Variables declared within the class i.e not within any methods and are defined as “static” are class variables 24. What are the different identifier states of a Thread? - The different identifiers of a Thread are: R - Running or runnable thread, S - Suspended thread, CW Thread waiting on a condition variable, MW - Thread waiting on a monitor lock, MS - Thread suspended waiting on a monitor lock 25. 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). 26. Why isn’t there operator overloading? - Because C++ has proven by example that operator overloading makes code almost impossible to maintain. In fact there very nearly wasn’t even method overloading in Java, but it was thought that this was too useful for some very basic methods like print(). Note that some of the classes like DataOutputStream have unoverloaded methods like writeInt() and writeByte(). 27. What does it mean that a method or field is “static"? - Static variables and methods are instantiated only once per class. In other words they are class

variables, not instance variables. If you change the value of a static variable in a particular object, the value of that variable changes for all instances of that class. Static methods can be referenced with the name of the class rather than the name of a particular object of the class (though that works too). That’s how library methods like System.out.println() work. out is a static field in the java.lang.System class. 28. How do I convert a numeric IP address like 192.18.97.39 into a hostname like java.sun.com? 29.

String hostname = InetAddress.getByName("192.18.97.39").getHostName();

30. Difference between JRE/JVM/JDK? 31. Why do threads block on I/O? - Threads block on i/o (that is enters the waiting state) so that other threads may execute while the I/O operation is performed. 32. What is synchronization and why is it important? - With respect to multithreading, synchronization is the capability to control the access of multiple threads to shared resources. Without synchronization, it is possible for one thread to modify a shared object while another thread is in the process of using or updating that object’s value. This often leads to significant errors. 33. Is null a keyword? - The null value is not a keyword. 34. Which characters may be used as the second character of an identifier,but not as the first character of an identifier? - The digits 0 through 9 may not be used as the first character of an identifier but they may be used after the first character of an identifier. 35. What modifiers may be used with an inner class that is a member of an outer class? - A (non-local) inner class may be declared as public, protected, private, static, final, or abstract. 36. How many bits are used to represent Unicode, ASCII, UTF-16, and UTF-8 characters? - Unicode requires 16 bits and ASCII require 7 bits. Although the ASCII character set uses only 7 bits, it is usually represented as 8 bits. UTF-8 represents characters using 8, 16, and 18 bit patterns. UTF-16 uses 16-bit and larger bit patterns. 37. What are wrapped classes? - Wrapped classes are classes that allow primitive types to be accessed as objects. 38. What restrictions are placed on the location of a package statement within a source code file? - A package statement must appear as the first line in a source code file (excluding blank lines and comments). 39. What is the difference between preemptive scheduling and time slicing? Under preemptive scheduling, the highest priority task executes until it enters the waiting or dead states or a higher priority task comes into existence. Under time slicing, a task executes for a predefined slice of time and then reenters the pool of ready tasks. The scheduler then determines which task should execute next, based on priority and other factors. 40. What is a native method? - A native method is a method that is implemented in a language other than Java. 41. What are order of precedence and associativity, and how are they used? Order of precedence determines the order in which operators are evaluated in expressions. Associatity determines whether an expression is evaluated left-toright or right-to-left

42. What is the catch or declare rule for method declarations? - If a checked exception may be thrown within the body of a method, the method must either catch the exception or declare it in its throws clause. 43. Can an anonymous class be declared as implementing an interface and extending a class? - An anonymous class may implement an interface or extend a superclass, but may not be declared to do both. 44. What is the range of the char type? - The range of the char type is 0 to 2^16 - 1.

interview questions 1. What is garbage collection? What is the process that is responsible for doing that in java? - Reclaiming the unused memory by the invalid objects. Garbage collector is responsible for this process 2. What kind of thread is the Garbage collector thread? - It is a daemon thread. 3. What is a daemon thread? - These are the threads which can run without user intervention. The JVM can exit when there are daemon thread by killing them abruptly. 4. How will you invoke any external process in Java? Runtime.getRuntime().exec(….) 5. What is the finalize method do? - Before the invalid objects get garbage collected, the JVM give the user a chance to clean up some resources before it got garbage collected. 6. What is mutable object and immutable object? - If a object value is changeable then we can call it as Mutable object. (Ex., StringBuffer, …) If you are not allowed to change the value of an object, it is immutable object. (Ex., String, Integer, Float, …) 7. What is the basic difference between string and stringbuffer object? - String is an immutable object. StringBuffer is a mutable object. 8. What is the purpose of Void class? - The Void class is an uninstantiable placeholder class to hold a reference to the Class object representing the primitive Java type void. 9. What is reflection? - Reflection allows programmatic access to information about the fields, methods and constructors of loaded classes, and the use reflected fields, methods, and constructors to operate on their underlying counterparts on objects, within security restrictions. 10. What is the base class for Error and Exception? - Throwable 11. What is the byte range? -128 to 127 12. What is the implementation of destroy method in java.. is it native or java code? - This method is not implemented. 13. What is a package? - To group set of classes into a single unit is known as packaging. Packages provides wide namespace ability. 14. What are the approaches that you will follow for making a program very efficient? - By avoiding too much of static methods avoiding the excessive and

unnecessary use of synchronized methods Selection of related classes based on the application (meaning synchronized classes for multiuser and nonsynchronized classes for single user) Usage of appropriate design patterns Using cache methodologies for remote invocations Avoiding creation of variables within a loop and lot more. 15. What is a DatabaseMetaData? - Comprehensive information about the database as a whole. 16. What is Locale? - A Locale object represents a specific geographical, political, or cultural region 17. How will you load a specific locale? - Using ResourceBundle.getBundle(…); 18. What is JIT and its use? - Really, just a very fast compiler… In this incarnation, pretty much a one-pass compiler – no offline computations. So you can’t look at the whole method, rank the expressions according to which ones are re-used the most, and then generate code. In theory terms, it’s an on-line problem. 19. Is JVM a compiler or an interpreter? - Interpreter 20. When you think about optimization, what is the best way to findout the time/memory consuming process? - Using profiler 21. What is the purpose of assert keyword used in JDK1.4.x? - In order to validate certain expressions. It effectively replaces the if block and automatically throws the AssertionError on failure. This keyword should be used for the critical arguments. Meaning, without that the method does nothing. 22. How will you get the platform dependent values like line separator, path separator, etc., ? - Using Sytem.getProperty(…) (line.separator, path.separator, …) 23. What is skeleton and stub? what is the purpose of those? - Stub is a client side representation of the server, which takes care of communicating with the remote server. Skeleton is the server side representation. But that is no more in use… it is deprecated long before in JDK. 24. What is the final keyword denotes? - final keyword denotes that it is the final implementation for that method or variable or class. You can’t override that method/variable/class any more. 25. What is the significance of ListIterator? - You can iterate back and forth. 26. What is the major difference between LinkedList and ArrayList? LinkedList are meant for sequential accessing. ArrayList are meant for random accessing. 27. What is nested class? - If all the methods of a inner class is static then it is a nested class. 28. What is inner class? - If the methods of the inner class can only be accessed via the instance of the inner class, then it is called inner class. 29. What is composition? - Holding the reference of the other class within some other class is known as composition. 30. What is aggregation? - It is a special type of composition. If you expose all the methods of a composite class and route the method call to the composite method through its reference, then it is called aggregation. 31. What are the methods in Object? - clone, equals, wait, finalize, getClass, hashCode, notify, notifyAll, toString

32. Can you instantiate the Math class? - You can’t instantiate the math class. All the methods in this class are static. And the constructor is not public. 33. What is singleton? - It is one of the design pattern. This falls in the creational pattern of the design pattern. There will be only one instance for that entire JVM. You can achieve this by having the private constructor in the class. For eg., public class Singleton { private static final Singleton s = new Singleton(); private Singleton() { } public static Singleton getInstance() { return s; } // all non static methods … } 34. What is DriverManager? - The basic service to manage set of JDBC drivers. 35. What is Class.forName() does and how it is useful? - It loads the class into the ClassLoader. It returns the Class. Using that you can get the instance ( “classinstance".newInstance() ). 36. Inq adds a question: Expain the reason for each keyword of public static void main(String args[])

Web development interview questions 1. Can we use the constructor, instead of init(), to initialize servlet? - 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. 2. How can a servlet refresh automatically if some new data has entered the database? - You can use a client-side Refresh or Server Push. 3. The code in a finally clause will never fail to execute, right? - Using System.exit(1); in try block will not allow finally code to execute. 4. How many messaging models do JMS provide for and what are they? - JMS provide for two messaging models, publish-and-subscribe and point-to-point queuing. 5. What information is needed to create a TCP Socket? - The Local System?s IP Address and Port Number. And the Remote System’s IPAddress and Port Number. 6. What Class.forName will do while loading drivers? - It is used to create an instance of a driver and register it with the DriverManager. When you have loaded a driver, it is available for making a connection with a DBMS. 7. How to Retrieve Warnings? - 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 8. 9. 10. 11. 12. 13. 14. 15. 16. 17. 18. 19.

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(); } }

20. How many JSP scripting elements are there and what are they? - There are three scripting language elements: declarations, scriptlets, expressions. 21. In the Servlet 2.4 specification SingleThreadModel has been deprecates, why? - Because it is not practical to have such model. Whether you set isThreadSafe to true or false, you should take care of concurrent client requests to the JSP page by synchronizing access to any shared objects defined at the page level. 22. What are stored procedures? How is it useful? - A stored procedure is a set of statements/commands which reside in the database. The stored procedure is precompiled and saves the database the effort of parsing and compiling sql statements everytime a query is run. Each Database has it’s own stored procedure language, usually a variant of C with a SQL preproceesor. Newer versions of db’s support writing stored procedures in Java and Perl too. Before the advent of 3tier/n-tier architecture it was pretty common for stored procs to implement the business logic( A lot of systems still do it). The biggest advantage is of course speed. Also certain kind of data manipulations are not achieved in SQL. Stored procs provide a mechanism to do these manipulations. Stored procs are also useful when you want to do Batch updates/exports/houseKeeping kind of stuff on the db. The overhead of a JDBC Connection may be significant in these cases. 23. 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: 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. 24. Why does JComponent have add() and remove() methods but Component does not? - because JComponent is a subclass of Container, and can contain other components and jcomponents. 25. How can I implement a thread-safe JSP page? - You can make your JSPs thread-safe by having them implement the SingleThreadModel interface. This is done by adding the directive within your JSP page.

Interview questions for Java junior developer position 1. What gives Java its “write once and run anywhere” nature? - Java is compiled to be a byte code which is the intermediate language between source code and machine code. This byte code is not platorm specific and hence can be fed to any platform. After being fed to the JVM, which is specific to a particular operating system, the code platform specific machine code is generated thus making java platform independent. 2. What are the four corner stones of OOP? - Abstraction, Encapsulation, Polymorphism and Inheritance. 3. Difference between a Class and an Object? - A class is a definition or prototype whereas an object is an instance or living representation of the prototype. 4. What is the difference between method overriding and overloading? Overriding is a method with the same name and arguments as in a parent, whereas overloading is the same method name but different arguments. 5. What is a “stateless” protocol? - Without getting into lengthy debates, it is generally accepted that protocols like HTTP are stateless i.e. there is no retention of state between a transaction which is a single request response combination. 6. What is constructor chaining and how is it achieved in Java? - A child object constructor always first needs to construct its parent (which in turn calls its parent constructor.). In Java it is done via an implicit call to the no-args constructor as the first statement. 7. What is passed by ref and what by value? - All Java method arguments are passed by value. However, Java does manipulate objects by reference, and all object variables themselves are references 8. Can RMI and Corba based applications interact? - Yes they can. RMI is available with IIOP as the transport protocol instead of JRMP. 9. You can create a String object as String str = “abc"; Why cant a button object be created as Button bt = “abc";? Explain - The main reason you cannot create a button by Button bt1= “abc"; is because “abc” is a literal string (something slightly different than a String object, by the way) and bt1 is a Button object. The only object in Java that can be assigned a literal String is java.lang.String. Important to note that you are NOT calling a java.lang.String constuctor when you type String s = “abc"; 10. What does the “abstract” keyword mean in front of a method? A class? Abstract keyword declares either a method or a class. If a method has a abstract keyword in front of it,it is called abstract method.Abstract method hs no body.It has only arguments and return type.Abstract methods act as placeholder methods that are implemented in the subclasses. Abstract classes can’t be instantiated.If a class is declared as abstract,no objects of that class can be created.If a class contains any abstract method it must be declared as abstract. 11. How many methods do u implement if implement the Serializable Interface? - The Serializable interface is just a “marker” interface, with no methods of its own to implement. Other ‘marker’ interfaces are

12. 13.

java.rmi.Remote java.util.EventListener

14. What are the practical benefits, if any, of importing a specific class rather than an entire package (e.g. import java.net.* versus import java.net.Socket)? - It makes no difference in the generated class files since only the classes that are actually used are referenced by the generated class file. There is another practical benefit to importing single classes, and this arises when two (or more) packages have classes with the same name. Take java.util.Timer and javax.swing.Timer, for example. If I import java.util.* and javax.swing.* and then try to use “Timer", I get an error while compiling (the class name is ambiguous between both packages). Let’s say what you really wanted was the javax.swing.Timer class, and the only classes you plan on using in java.util are Collection and HashMap. In this case, some people will prefer to import java.util.Collection and import java.util.HashMap instead of importing java.util.*. This will now allow them to use Timer, Collection, HashMap, and other javax.swing classes without using fully qualified class names in. 15. What is the difference between logical data independence and physical data independence? - Logical Data Independence - meaning immunity of external schemas to changeds in conceptual schema. Physical Data Independence meaning immunity of conceptual schema to changes in the internal schema. 16. What is a user-defined exception? - Apart from the exceptions already defined in Java package libraries, user can define his own exception classes by extending Exception class. 17. 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.

1. What are the implicit objects? - 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. 2. Is JSP technology extensible? - Yes. JSP technology is extensible through the development of custom actions, or tags, which are encapsulated in tag libraries. 3. How can I implement a thread-safe JSP page? What are the advantages and Disadvantages of using it? - You can make your JSPs thread-safe by having them implement the SingleThreadModel interface. This is done by adding the directive 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 4. How does JSP handle run-time exceptions? - You can use the errorPage attribute of the page directive to have uncaught run-time exceptions automatically forwarded to an error processing page. For example: 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: 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. 5. How do I prevent the output of my JSP or Servlet pages from being cached by the browser? - You will need to set the appropriate HTTP header attributes to prevent the dynamic content output by the JSP page from being cached by the browser. Just execute the following scriptlet at the beginning of your JSP pages to prevent them from being cached at the browser. You need both the statements to take care of some of the older browser versions. 6. How do I use comments within a JSP page? - You can use “JSP-style” comments to selectively block out code while debugging or simply to comment your scriptlets. JSP comments are not visible at the client. For example: 7. 8. 9. 10. 11.



You can also use HTML-style comments anywhere within your JSP page. These comments are visible at the client. For example:

Of course, you can also use comments supported by your JSP scripting language within your scriptlets. For example, assuming Java is the scripting language, you can have:

12. Response has already been commited error. What does it mean? - This error show only when you try to redirect a page after you already have written something in your page. This happens because HTTP specification force the header to be set up before the lay out of the page can be shown (to make sure of how it should be displayed, content-type="text/html” or “text/xml” or “plain-text” or “image/jpg", etc.) When you try to send a redirect status (Number is line_status_402), your HTTP server cannot send it right now if it hasn’t finished to set up the header. If not starter to set up the header, there are no problems, but if it ’s already begin to set up the header, then your HTTP server expects these headers to be finished setting up and it cannot be the case if the stream of the page is not over… In this last case it’s like you have a file started with some output (like testing your variables.) Before you indicate that the file is over (and before the size of the page can be setted up in the header), you try to send a redirect status. It s simply impossible due to the specification of HTTP 1.0 and 1.1 13. How do I use a scriptlet to initialize a newly instantiated bean? - A jsp:useBean action may optionally have a body. If the body is specified, its contents will be automatically invoked when the specified bean is instantiated. Typically, the body will contain scriptlets or jsp:setProperty tags to initialize the newly instantiated bean, although you are not restricted to using those alone. The following example shows the “today” property of the Foo bean initialized to the current date when it is instantiated. Note that here, we make use of a JSP expression within the jsp:setProperty action. 14. 15. 17. 18.

19. How can I enable session tracking for JSP pages if the browser has disabled cookies? - We know that session tracking uses cookies by default to associate a session identifier with a unique user. If the browser does not support cookies, or if cookies are disabled, you can still enable session tracking using URL rewriting. URL rewriting essentially includes the session ID within the link itself as a name/value pair. However, for this to be effective, you need to append the session ID for each and every link that is part of your servlet response. Adding the session ID to a link is greatly simplified by means of of a couple of methods: response.encodeURL() associates a session ID with a given URL, and if you are using redirection, response.encodeRedirectURL() can be used by giving the redirected URL as input. Both encodeURL() and encodeRedirectedURL() first determine whether cookies are supported by the browser; if so, the input URL is returned unchanged since the session ID will be persisted as a cookie. Consider the following example, in which two JSP files, say hello1.jsp and hello2.jsp, interact with each other. Basically, we create a new session within hello1.jsp and

place an object within this session. The user can then traverse to hello2.jsp by clicking on the link present within the page.Within hello2.jsp, we simply extract the object that was earlier placed in the session and display its contents. Notice that we invoke the encodeURL() within hello1.jsp on the link used to invoke hello2.jsp; if cookies are disabled, the session ID is automatically appended to the URL, allowing hello2.jsp to still retrieve the session object. Try this example first with cookies enabled. Then disable cookie support, restart the brower, and try again. Each time you should see the maintenance of the session across pages. Do note that to get this example to work with cookies disabled at the browser, your JSP engine has to support URL rewriting. 20. 21. 22. 23. 24. 25. 26. 27. 28. 29. 30. 31. 32.

hello1.jsp hello2.jsp hello2.jsp

104.How can I get to print the stacktrace for an exception occuring within my JSP page? - By printing out the exception’s stack trace, you can usually diagonse a problem better when debugging JSP pages. By looking at a stack trace, a programmer should be able to discern which method threw the exception and which method called that method. However, you cannot print the stacktrace using the JSP out implicit variable, which is of type JspWriter. You will have to use a

PrintWriter object instead. The following snippet demonstrates how you can print a stacktrace from within a JSP error page: 105. 106. 107. 108. 109. 110. 111.



112.How do you pass an InitParameter to a JSP? - The JspPage interface defines the jspInit() and jspDestroy() method which the page writer can use in their pages and are invoked in much the same manner as the init() and destory() methods of a servlet. The example page below enumerates through all the parameters and prints them to the console. 113. 114. 115. 116. 117. 118. 119. 120. 121. 122. 123. 124.



125.How can my JSP page communicate with an EJB Session Bean? - The following is a code snippet that demonstrates how a JSP page can interact with an EJB session bean: 126. 127. 137.

J2EE interview questions Thanks to Sachin Rastogi for contributing these. 1. What makes J2EE suitable for distributed multitiered Applications? - The J2EE platform uses a multitiered distributed application model. Application logic is divided into components according to function, and the various application components that make up a J2EE application are installed on different machines depending on the tier in the multitiered J2EE environment to which the application component belongs. The J2EE application parts are: o Client-tier components run on the client machine. o Web-tier components run on the J2EE server. o Business-tier components run on the J2EE server. o Enterprise information system (EIS)-tier software runs on the EIS server. 2. What is J2EE? - J2EE is an environment for developing and deploying enterprise applications. The J2EE platform consists of a set of services, application programming interfaces (APIs), and protocols that provide the functionality for developing multitiered, web-based applications. 3. What are the components of J2EE application? - A J2EE component is a self-contained functional software unit that is assembled into a J2EE application with its related classes and files and communicates with other components. The J2EE specification defines the following J2EE components: 1.Application clients and applets are client components. 2.Java Servlet and JavaServer Pages technology components

are web components. 3.Enterprise JavaBeans components (enterprise beans) are business components. 4.Resource adapter components provided by EIS and tool vendors. 2. What do Enterprise JavaBeans components contain? - Enterprise JavaBeans components contains Business code, which is logic that solves or meets the needs of a particular business domain such as banking, retail, or finance, is handled by enterprise beans running in the business tier. All the business code is contained inside an Enterprise Bean which receives data from client programs, processes it (if necessary), and sends it to the enterprise information system tier for storage. An enterprise bean also retrieves data from storage, processes it (if necessary), and sends it back to the client program. 3. Is J2EE application only a web-based? - No, It depends on type of application that client wants. A J2EE application can be web-based or non-web-based. if an application client executes on the client machine, it is a non-web-based J2EE application. The J2EE application can provide a way for users to handle tasks such as J2EE system or application administration. It typically has a graphical user interface created from Swing or AWT APIs, or a command-line interface. When user request, it can open an HTTP connection to establish communication with a servlet running in the web tier.

4. Are JavaBeans J2EE components? - No. JavaBeans components are not considered J2EE components by the J2EE specification. They are written to manage the data flow between an application client or applet and components running on the J2EE server or between server components and a database. JavaBeans components written for the J2EE platform have instance variables and get and set methods for accessing the data in the instance variables. JavaBeans components used in this way are typically simple in design and implementation, but should conform to the naming and design conventions outlined in the JavaBeans component architecture. 5. Is HTML page a web component? - No. Static HTML pages and applets are bundled with web components during application assembly, but are not considered web components by the J2EE specification. Even the server-side utility classes are not considered web components, either. 6. What can be considered as a web component? - J2EE Web components can be either servlets or JSP pages. Servlets are Java programming language classes that dynamically process requests and construct responses. JSP pages are text-based documents that execute as servlets but allow a more natural approach to creating static content. 7. What is the container? - Containers are the interface between a component and the low-level platform specific functionality that supports the component. Before a Web, enterprise bean, or application client component can be executed, it must be assembled into a J2EE application and deployed into its container. 8. What are container services? - A container is a runtime support of a systemlevel entity. Containers provide components with services such as lifecycle management, security, deployment, and threading. 9. What is the web container? - Servlet and JSP containers are collectively referred to as Web containers. It manages the execution of JSP page and servlet components for J2EE applications. Web components and their container run on the J2EE server. 10. What is Enterprise JavaBeans (EJB) container? - It manages the execution of enterprise beans for J2EE applications. Enterprise beans and their container run on the J2EE server. 11. What is Applet container? - IManages the execution of applets. Consists of a Web browser and Java Plugin running on the client together. 12. How do we package J2EE components? - J2EE components are packaged separately and bundled into a J2EE application for deployment. Each component, its related files such as GIF and HTML files or server-side utility classes, and a deployment descriptor are assembled into a module and added to the J2EE application. A J2EE application is composed of one or more enterprise bean,Web, or application client component modules. The final enterprise solution can use one J2EE application or be made up of two or more J2EE applications, depending on design requirements. A J2EE application and each of its modules has its own deployment descriptor. A deployment descriptor is an XML document with an .xml extension that describes a component’s deployment settings.

13. What is a thin client? - A thin client is a lightweight interface to the application that does not have such operations like query databases, execute complex business rules, or connect to legacy applications. 14. What are types of J2EE clients? - Following are the types of J2EE clients: o o o o

Applets Application clients Java Web Start-enabled rich clients, powered by Java Web Start technology. Wireless clients, based on Mobile Information Device Profile (MIDP) technology.

4. What is deployment descriptor? - A deployment descriptor is an Extensible Markup Language (XML) text-based file with an .xml extension that describes a component’s deployment settings. A J2EE application and each of its modules has its own deployment descriptor. For example, an enterprise bean module deployment descriptor declares transaction attributes and security authorizations for an enterprise bean. Because deployment descriptor information is declarative, it can be changed without modifying the bean source code. At run time, the J2EE server reads the deployment descriptor and acts upon the component accordingly. 5. What is the EAR file? - An EAR file is a standard JAR file with an .ear extension, named from Enterprise ARchive file. A J2EE application with all of its modules is delivered in EAR file. 6. What is JTA and JTS? - JTA is the abbreviation for the Java Transaction API. JTS is the abbreviation for the Jave Transaction Service. JTA provides a standard interface and allows you to demarcate transactions in a manner that is independent of the transaction manager implementation. The J2EE SDK implements the transaction manager with JTS. But your code doesn’t call the JTS methods directly. Instead, it invokes the JTA methods, which then call the lower-level JTS routines. Therefore, JTA is a high level transaction interface that your application uses to control transaction. and JTS is a low level transaction interface and ejb uses behind the scenes (client code doesn’t directly interact with JTS. It is based on object transaction service(OTS) which is part of CORBA. 7. What is JAXP? - JAXP stands for Java API for XML. XML is a language for representing and describing text-based data which can be read and handled by any program or tool that uses XML APIs. It provides standard services to determine the type of an arbitrary piece of data, encapsulate access to it, discover the operations available on it, and create the appropriate JavaBeans component to perform those operations. 8. What is J2EE Connector? - The J2EE Connector API is used by J2EE tools vendors and system integrators to create resource adapters that support access to enterprise information systems that can be plugged into any J2EE product. Each type of database or EIS has a different resource

adapter. Note: A resource adapter is a software component that allows J2EE application components to access and interact with the underlying resource manager. Because a resource adapter is specific to its resource manager, there is typically a different resource adapter for each type of database or enterprise information system. 9. What is JAAP? - The Java Authentication and Authorization Service (JAAS) provides a way for a J2EE application to authenticate and authorize a specific user or group of users to run it. It is a standard Pluggable Authentication Module (PAM) framework that extends the Java 2 platform security architecture to support user-based authorization. 10. What is Java Naming and Directory Service? - The JNDI provides naming and directory functionality. It provides applications with methods for performing standard directory operations, such as associating attributes with objects and searching for objects using their attributes. Using JNDI, a J2EE application can store and retrieve any type of named Java object. Because JNDI is independent of any specific implementations, applications can use JNDI to access multiple naming and directory services, including existing naming and directory services such as LDAP, NDS, DNS, and NIS. 11. What is Struts? - A Web page development framework. Struts combines Java Servlets, Java Server Pages, custom tags, and message resources into a unified framework. It is a cooperative, synergistic platform, suitable for development teams, independent developers, and everyone between. 12. How is the MVC design pattern used in Struts framework? - In the MVC design pattern, application flow is mediated by a central Controller. The Controller delegates requests to an appropriate handler. The handlers are tied to a Model, and each handler acts as an adapter between the request and the Model. The Model represents, or encapsulates, an application’s business logic or state. Control is usually then forwarded back through the Controller to the appropriate View. The forwarding can be determined by consulting a set of mappings, usually loaded from a database or configuration file. This provides a loose coupling between the View and Model, which can make an application significantly easier to create and maintain. Controller: Servlet controller which supplied by Struts itself; View: what you can see on the screen, a JSP page and presentation components; Model: System state and a business logic JavaBeans.

Java interview questions 1. What are synchronized methods and synchronized statements? Synchronized methods are methods that are used to control access to an object. For example, 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.

2. What are different ways in which a thread can enter the waiting state? A thread can enter the waiting state by invoking its sleep() method, blocking on I/O, unsuccessfully attempting to acquire an object’s lock, or invoking an object’s wait() method. It can also enter the waiting state by invoking its (deprecated) suspend() method. 3. Can a lock be acquired on a class? Yes, a lock can be acquired on a class. This lock is acquired on the class’s Class object. 4. What’s new with the stop(), suspend() and resume() methods in new JDK 1.2? The stop(), suspend() and resume() methods have been deprecated in JDK 1.2. 5. What is the preferred size of a component? The preferred size of a component is the minimum component size that will allow the component to display normally. 6. What method is used to specify a container’s layout? The setLayout() method is used to specify a container’s layout. For example, setLayout(new FlowLayout()); will be set the layout as FlowLayout. 7. Which containers use a FlowLayout as their default layout? The Panel and Applet classes use the FlowLayout as their default layout. 8. What state does a thread enter when it terminates its processing? When a thread terminates its processing, it enters the dead state. 9. What is the Collections API? The Collections API is a set of classes and interfaces that support operations on collections of objects. One example of class in Collections API is Vector and Set and List are examples of interfaces in Collections API. 10. What is the List interface? The List interface provides support for ordered collections of objects. It may or may not allow duplicate elements but the elements must be ordered. 11. How does Java handle integer overflows and underflows? It uses those low order bytes of the result that can fit into the size of the type allowed by the operation. 12. What is the Vector class? The Vector class provides the capability to implement a growable array of objects. The main visible advantage of this class is programmer needn’t to worry about the number of elements in the Vector. 13. What modifiers may be used with an inner class that is a member of an outer class? A (non-local) inner class may be declared as public, protected, private, static, final, or abstract. 14. If a method is declared as protected, where may the method be accessed? A protected method may only be accessed by classes or interfaces of the same package or by subclasses of the class in which it is declared. 15. What is an Iterator interface? The Iterator interface is used to step through the elements of a Collection. 16. How many bits are used to represent Unicode, ASCII, UTF-16, and UTF-8 characters? Unicode requires 16 bits, ASCII require 7 bits (although the ASCII character set uses only 7 bits, it is usually represented as 8 bits), UTF-8 represents characters using 8, 16, and 18 bit patterns, UTF-16 uses 16-bit and larger bit patterns

17. What is the difference between yielding and sleeping? Yielding means a thread returning to a ready state either from waiting, running or after creation, where as sleeping refers a thread going to a waiting state from running state. With reference to Java, when a task invokes its yield() method, it returns to the ready state and when a task invokes its sleep() method, it returns to the waiting state 18. What are wrapper classes? Wrapper classes are classes that allow primitive types to be accessed as objects. For example, Integer, Double. These classes contain many methods which can be used to manipulate basic data types 19. Does garbage collection guarantee that a program will not run out of memory? No, it doesn’t. It is possible for programs to use up memory resources faster than they are garbage collected. It is also possible for programs to create objects that are not subject to garbage collection. The main purpose of Garbage Collector is recover the memory from the objects which are no longer required when more memory is needed. 20. Name Component subclasses that support painting? The following classes support painting: Canvas, Frame, Panel, and Applet. 21. What is a native method? A native method is a method that is implemented in a language other than Java. For example, one method may be written in C and can be called in Java. 22. How can you write a loop indefinitely? for(;;) //for loop while(true); //always true 23. Can an anonymous class be declared as implementing an interface and extending a class? An anonymous class may implement an interface or extend a superclass, but may not be declared to do both. 24. What is the purpose of finalization? The purpose of finalization is to give an unreachable object the opportunity to perform any cleanup processing before the object is garbage collected. For example, closing a opened file, closing a opened database Connection. 25. What invokes a thread’s run() method? After a thread is started, via its start() method or that of the Thread class, the JVM invokes the thread’s run() method when the thread is initially executed. 26. What is the GregorianCalendar class? The GregorianCalendar provides support for traditional Western calendars. 27. What is the SimpleTimeZone class? The SimpleTimeZone class provides support for a Gregorian calendar. 28. What is the Properties class? The properties class is a subclass of Hashtable that can be read from or written to a stream. It also provides the capability to specify a set of default values to be used. 29. What is the purpose of the Runtime class? The purpose of the Runtime class is to provide access to the Java runtime system. 30. What is the purpose of the System class? The purpose of the System class is to provide access to system resources.

31. What is the purpose of the finally clause of a try-catch-finally statement? The finally clause is used to provide the capability to execute code no matter whether or not an exception is thrown or caught. For example, try { //some statements } catch { // statements when exception is cought } finally { //statements executed whether exception occurs or not } 32. What is the Locale class? The Locale class is used to tailor program output to the conventions of a particular geographic, political, or cultural region. 33. What must a class do to implement an interface? It must provide all of the methods in the interface and identify the interface in its implements clause.

View more...

Comments

Copyright ©2017 KUPDF Inc.
SUPPORT KUPDF