java interview

233
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 & 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.

Upload: bhavin-acharya

Post on 14-Nov-2014

724 views

Category:

Documents


3 download

TRANSCRIPT

Page 1: Java Interview

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 & 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 event-inheritance 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 initialization 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.

Page 2: Java Interview

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

Page 3: Java Interview

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. public interface abc5. {6. static int i=0; void dd();7. class a18. {9. a1()10. {11. int j;12. System.out.println("inside");13. };14. public static void main(String a1[])15. {16. System.out.println("in interfia");17. }18. }19. }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,

Page 4: Java Interview

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-to-right or right-to-left

Page 5: Java Interview

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 non-synchronized classes for single user) Usage of appropriate design patterns Using cache

Page 6: Java Interview

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

Page 7: Java Interview

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 ( “class-instance".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. SQLWarning warning = stmt.getWarnings();9. if (warning != null)10. {11. while (warning != null)12. {13. System.out.println("Message: " + warning.getMessage());14. System.out.println("SQLState: " + warning.getSQLState());15. System.out.print("Vendor error code: ");16. System.out.println(warning.getErrorCode());17. warning = warning.getNextWarning();

Page 8: Java Interview

18. }19. }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 3-tier/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 <%@ page isThreadSafe="false" % > 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.

Page 9: Java Interview

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. java.rmi.Remote13. java.util.EventListener14. 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.

Page 10: Java Interview

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 <%@ page isThreadSafe="false" %> within your JSP page. With this, instead of a single instance of the servlet generated for your JSP page loaded in memory, you will have N instances of the servlet loaded and initialized, with the service method of each instance effectively synchronized. You can typically control the number of instances (N) that are instantiated for all servlets implementing SingleThreadModel through the admin screen for your JSP engine. More importantly, avoid using the tag for variables. If you do use this tag, then you should set isThreadSafe to true, as mentioned above. Otherwise, all requests to that page will access those variables, causing a nasty race condition. SingleThreadModel is not recommended for normal use. There are many pitfalls, including the example above of not being able to use <%! %>. You should try really hard to make them thread-safe the old fashioned way: by making them thread-safe 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: <%@ page errorPage="error.jsp" %>redirects the browser to the JSP page error.jsp if an uncaught exception is encountered during request processing. Within error.jsp, if you indicate that it is an error-processing page, via the directive: <%@ page isErrorPage="true" %> Throwable object describing the exception may be accessed within the error page via the exception implicit object. Note: You must always use a relative URL as the value for the errorPage attribute.

Page 11: Java Interview

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.

<%response.setHeader("Cache-Control","no-store"); //HTTP 1.1response.setHeader("Pragma","no-cache"); //HTTP 1.0response.setDateHeader ("Expires", 0); //prevents caching at the proxy server%> 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. <%-- the scriptlet is now commented out8. <%9. out.println("Hello World");10. %>11. --%>You can also use HTML-style comments anywhere within your JSP page. These comments are visible at the client. For example:<!-- (c) 2004 -->Of course, you can also use comments supported by your JSP scripting language within your scriptlets. For example, assuming Java is the scripting language, you can have:

<%//some comment/**yet another comment**/%>

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 <HTML Tag><Some Headers><Body>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

Page 12: Java Interview

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. <jsp:useBean id="foo" class="com.Bar.Foo" >15. <jsp:setProperty name="foo" property="today"16. value="<%=java.text.DateFormat.getDateInstance().format(new java.util.Date()) %>"/ >17. <%-- scriptlets calling bean setter methods go here --%>18. </jsp:useBean >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. hello1.jsp21. <%@ page session="true" %>22. <%23. Integer num = new Integer(100);24. session.putValue("num",num);25. String url =response.encodeURL("hello2.jsp");26. %>27. <a href='<%=url%>'>hello2.jsp</a>28. hello2.jsp29. <%@ page session="true" %>30. <%

Page 13: Java Interview

31. Integer i= (Integer )session.getValue("num");32. out.println("Num value in session is "+i.intValue());33. How can I declare methods within my JSP page? - You can declare methods for use within your JSP page as declarations. The methods can then be invoked within any other methods you declare, or within JSP scriptlets and expressions. Do note that you do not have direct access to any of the JSP implicit objects like request, response, session and so forth from within JSP methods. However, you should be able to pass any of the implicit JSP variables as parameters to the methods you declare. For example: 34. <%!35. public String whereFrom(HttpServletRequest req) {36. HttpSession ses = req.getSession();37. ...38. return req.getRemoteHost();39. }40. %>41. <%42. out.print("Hi there, I see that you are coming in from ");43. %>44. <%= whereFrom(request) %>45. Another Example46. file1.jsp:47. <%@page contentType="text/html"%>48. <%!49. public void test(JspWriter writer) throws IOException{50. writer.println("Hello!");51. }52. %>53. file2.jsp54. <%@include file="file1.jsp"%>55. <html>56. <body>57. <%test(out);% >58. </body>59. </html>60. Is there a way I can set the inactivity lease period on a per-session basis? - Typically, a default inactivity lease period for all sessions is set within your JSP engine admin screen or associated properties file. However, if your JSP engine supports the Servlet 2.1 API, you can manage the inactivity lease period on a per-session basis. This is done by invoking the HttpSession.setMaxInactiveInterval() method, right after the session has been created. For example: 61. <%62. session.setMaxInactiveInterval(300);63. %>

would reset the inactivity period for this session to 5 minutes. The inactivity interval is set in seconds.

64. How can I set a cookie and delete a cookie from within a JSP page? - A cookie, mycookie, can be deleted using the following scriptlet: 65. <%66. //creating a cookie

Page 14: Java Interview

67. Cookie mycookie = new Cookie("aName","aValue");68. response.addCookie(mycookie);69. //delete a cookie70. Cookie killMyCookie = new Cookie("mycookie", null);71. killMyCookie.setMaxAge(0);72. killMyCookie.setPath("/");73. response.addCookie(killMyCookie);74. %>75. How does a servlet communicate with a JSP page? - The following code snippet shows how a servlet instantiates a bean and initializes it with FORM data posted by a browser. The bean is then placed into the request, and the call is then forwarded to the JSP page, Bean1.jsp, by means of a request dispatcher for downstream processing. 76. public void doPost (HttpServletRequest request, HttpServletResponse response) {77. try {78. govi.FormBean f = new govi.FormBean();79. String id = request.getParameter("id");80. f.setName(request.getParameter("name"));81. f.setAddr(request.getParameter("addr"));82. f.setAge(request.getParameter("age"));83. //use the id to compute84. //additional bean properties like info85. //maybe perform a db query, etc.86. // . . .87. f.setPersonalizationInfo(info);88. request.setAttribute("fBean",f);89. getServletConfig().getServletContext().getRequestDispatcher90. ("/jsp/Bean1.jsp").forward(request, response);91. } catch (Exception ex) {92. . . .93. }94. }The JSP page Bean1.jsp can then process fBean, after first extracting it from the default request scope via the useBean action.jsp:useBean id="fBean" class="govi.FormBean" scope="request"/ jsp:getProperty name="fBean" property="name"/ jsp:getProperty name="fBean" property="addr"/ jsp:getProperty name="fBean" property="age"/ jsp:getProperty name="fBean" property="personalizationInfo" /95. How do I have the JSP-generated servlet subclass my own custom servlet class, instead of the default? - One should be very careful when having JSP pages extend custom servlet classes as opposed to the default one generated by the JSP engine. In doing so, you may lose out on any advanced optimization that may be provided by the JSP engine. In any case, your new superclass has to fulfill the contract with the JSP engine by:Implementing the HttpJspPage interface, if the protocol used is HTTP, or implementing JspPage otherwise Ensuring that all the methods in the Servlet interface are declared final Additionally, your servlet superclass also needs to do the following: o The service() method has to invoke the _jspService() method o The init() method has to invoke the jspInit() method

Page 15: Java Interview

o The destroy() method has to invoke jspDestroy()

If any of the above conditions are not satisfied, the JSP engine may throw a translation error.Once the superclass has been developed, you can have your JSP extend it as follows:

<%@ page extends="packageName.ServletName" %>96. How can I prevent the word "null" from appearing in my HTML input text fields when I populate them with a resultset that has null values? - You could make a simple wrapper function, like 97. <%!98. String blanknull(String s) {99. return (s == null) ? "" : s;100. }101. %>102. then use it inside your JSP form, like103. <input type="text" name="shoesize" value="<%=blanknull(shoesize)% >" >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. <%@ page isErrorPage="true" %>106. <%107. out.println(" ");108. PrintWriter pw = response.getWriter();109. exception.printStackTrace(pw);110. out.println(" ");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. <%@ page import="java.util.*" %>114. <%!115. ServletConfig cfg =null;116. public void jspInit(){117. ServletConfig cfg=getServletConfig();118. for (Enumeration e=cfg.getInitParameterNames(); e.hasMoreElements();) {119. String name=(String)e.nextElement();120. String value = cfg.getInitParameter(name);121. System.out.println(name+"="+value);122. }123. }124. %>

Page 16: Java Interview

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. <%@ page import="javax.naming.*, javax.rmi.PortableRemoteObject, foo.AccountHome, foo.Account" %>127. <%!128. //declare a "global" reference to an instance of the home interface of the session bean129. AccountHome accHome=null;130. public void jspInit() {131. //obtain an instance of the home interface132. InitialContext cntxt = new InitialContext( );133. Object ref= cntxt.lookup("java:comp/env/ejb/AccountEJB");134. accHome = (AccountHome)PortableRemoteObject.narrow(ref,AccountHome.class);135. }136. %>137. <%138. //instantiate the session bean139. Account acct = accHome.create();140. //invoke the remote methods141. acct.doWhatever(...);142. // etc etc...143. %>

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.

Page 17: Java Interview

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 logicthat 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 system-level 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.

Page 18: Java Interview

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 Applets o Application clients o Java Web Start-enabled rich clients, powered by Java Web Start technology. o 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 authorizationsfor 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

Page 19: Java Interview

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

Page 20: Java Interview

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.

Page 21: Java Interview

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 loopwhile(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.

Page 22: Java Interview

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. 34.What if the main method is declared as private?

The program compiles properly but at runtime it will give "Main method not public." message.

35.What if the static modifier is removed from the signature of the main method?

Program compiles. But at runtime throws an error "NoSuchMethodError".

36.What if I write static public void instead of public static void?

Program compiles and runs properly.

37. What if I do not provide the String array as the argument to the method?

Program compiles but throws a runtime error "NoSuchMethodError".

38. What is the first argument of the String array in main method?

The String array is empty. It does not have any element. This is unlike C/C++ where the first element by default is the program name.

Page 23: Java Interview

39. If I do not provide any arguments on the command line, then the String array of Main method will be empty of null?

It is empty. But not null.

40. How can one prove that the array is not null but empty?

Print args.length. It will print 0. That means it is empty. But if it would have been null then it would have thrown a NullPointerException on attempting to print args.length.

41. What environment variables do I need to set on my machine in order to be able to run Java programs?

CLASSPATH and PATH are the two variables.

42. Can an application have multiple classes having main method?

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.

43. Can I have multiple main methods in the same class?

No the program fails to compile. The compiler says that the main method is already defined in the class.

44. Do I need to import java.lang package any time? Why ?

No. It is by default loaded internally by the JVM.

45. Can I import same package/class twice? Will the JVM load the package twice at runtime?

One can import the same package or same class multiple times. Neither compiler nor JVM complains abt it. And the JVM will internally load the class only once no matter how many times you import the same class.

46. What are Checked and UnChecked Exception?

A checked exception is some subclass of Exception (or Exception itself), excluding class RuntimeException and its subclasses.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 theexception or declare it in a throws clause. In fact, client programmers may not even know that the exception could be thrown. eg, StringIndexOutOfBoundsException thrown by String's charAt() method· Checked

Page 24: Java Interview

exceptions must be caught at compile time. Runtime exceptions do not need to be. Errors often cannot be.

47. What is Overriding?

When a class defines a method using the same name, return type, and arguments as a method in its superclass, the method in the class overrides the method in the superclass.When the method is invoked for an object of the class, it is the new definition of the method that is called, and not the method definition from superclass. Methods may be overridden to be more public, not more private.

48. What are different types of inner classes?

Nested top-level classes, Member classes, Local classes, Anonymous classes

Nested top-level classes- If you declare a class within a class and specify the static modifier, the compiler treats the class just like any other top-level class.Any class outside the declaring class accesses the nested class with the declaring class name acting similarly to a package. eg, outer.inner. Top-level inner classes implicitly have access only to static variables.There can also be inner interfaces. All of these are of the nested top-level variety.

Member classes - Member inner classes are just like other member methods and member variables and access to the member class is restricted, just like methods and variables. This means a public member class acts similarly to a nested top-level class. The primary difference between member classes and nested top-level classes is that member classes have access to the specific instance of the enclosing class.

Local classes - Local classes are like local variables, specific to a block of code. Their visibility is only within the block of their declaration. In order for the class to be useful beyond the declaration block, it would need to implement amore publicly available interface.Because local classes are not members, the modifiers public, protected, private, and static are not usable.

Anonymous classes - Anonymous inner classes extend local inner classes one level further. As anonymous classes have no name, you cannot provide a constructor.

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.

Page 25: Java Interview

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 event-inheritance 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 non-static 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

Page 26: Java Interview

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.

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.

Page 27: Java Interview

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

Page 28: Java Interview

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 system-level 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 Appletso Application clientso Java Web Start-enabled rich clients, powered by Java Web Start

technology.o 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

Page 29: Java Interview

its own deployment descriptor. For example, an enterprise bean module deployment descriptor declares transaction attributes and security authorizationsfor 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 anddirectory services such as LDAP, NDS, DNS, and NIS.

Page 30: Java Interview

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.

Index:1. Core Java InterView Questions 2. JSP Inteview Questions: 3. Servlet Interview Questions 4. Java database interview questions 5. Java Web development interview questions 6. EJB interview questions 7. Advanced EJB interview questions 8. Learing notes:Serialization 9. LearningNotes:Collection 10. Implementing thread safety in servlets 10.Learning notes: Threads And Synchronization

Core Java Interview Questions1

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.

What are the four corner stones of OOP? Abstraction, Encapsulation, Polymorphism and Inheritance.

1 J2ee book

Page 31: Java Interview

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.

Q: What is the Collections API? A: The Collections API is a set of classes and interfaces that support operations on collections of objects. Q: Considering the basic properties of Vector and ArrayList, where will you use Vector and where will you use ArrayList?A: The basic difference between a Vector and an ArrayList is that, vector is synchronized while ArrayList is not. Thus whenever there is a possibility of multiple threads accessing the same instance, one should use Vector. While if not multiple threads are going to access the same instance then use ArrayList. Non synchronized data structure will give better performance than the synchronized one. Can a top level class be private or protected?A: No. A top level class can not be private or protected. It can have either "public" or no modifier. If it does not have a modifier it is supposed to have a default access.If a top level class is declared as private the compiler will complain that the "modifier private is not allowed here". This means that a top level class can not be private. Same is the case with protected.

Describe synchronization in respect to multithreading.A: With respect to multithreading, synchronization is the capability to control the access of multiple threads to shared resources. Without synchonization, it is possible for one thread to modify a shared variable while another thread is in the process of using or updating same shared variable. This usually leads to significant errors.

What's the difference between the methods sleep() and wait() The code sleep(1000); puts thread aside for exactly one second. The code wait(1000), causes a wait of up to one second. A thread could stop waiting earlier if it receives the notify() or notifyAll() call. The method wait() is defined in the class Object and the method sleep() is defined in the class Thread.

Is there a way that I can get the number of threads currently executing within the JVM?You can use activeCount() for this. activeCount() returns the number of active threads that are part of the current thread's thread group. static int activeCount()

What is a third benefit of multithreading? Multithreading allows a processor to remain productive because the processor does not need to spend all its time waiting for input/output operations to complete.

Internally, the join() method calls wait(0) instead of the sleep(long millis) method. Why? Object's wait() methods cause a thread to lose the monitor's ownership. In contrast, Thread's sleep() methods do not cause a thread to lose monitor ownership. That implies threads retain any held locks when they call the sleep() methods. If join() was coded to call a sleep() method, two threads calling that method might deadlock (because they might hold each other's locks). By having join() call wait(0), Sun has eliminated that deadlock potential.

What does it mean to lock an object?

Page 32: Java Interview

Every object instance in Java has a little piece of data hanging off of it called a "monitor lock." This is similar to a semaphore. When you use the synchronized keyword, the current thread attempts to obtain the monitor lock for the object in question (either "this" or the object named explicitly). If the lock is unavailable, because another thread has acquired it, then the current thread pauses indefinitely. When it wakes up again, it will have acquired the lock, and will retain it until the end of the code block where synchronized was used. One confusing part is that the only thing that this lock locks is access to the lock itself. It does not control access to instance variables or method access in and of itself. Other threads can reach in and modify variables and call methods. If you want the lock to control access to variables, then you must explicitly use the synchronized keyword every single place in your code that accesses them. A straightforward way to guarantee that no variable access happens without a lock is by making all your variables private and using synchronized on all your accessor/mutator methods (getFoo/setFoo).

What are the different uses of the synchronized keyword? The keyword synchronized is used to acquire a exclusive monitor lock on an object. It can be used to mark either a method or a block of code. In both cases, it means to acquire a lock for the duration of the method or block, and to release the lock at the end. It also takes a parameter, which names the object whose lock will be acquired. (The parameter is implicit when marking a method, as shown below.) synchronized (foo) { ...}Acquires a lock on the object instance "foo" at the open brace, and releases the lock at the close brace. synchronized (this) { ...}Acquires a lock on the current object instance ("this") at the open brace, and releases the lock at the close brace. synchronized void bar() { ... }Acquires a lock on the current object instance at the open brace, and releases it at the close brace. This is equivalent (*) to void bar() { synchronized (this) { ... }}class Foo { synchronized static void bar() { ... } } Acquires and releases a lock on the class instance of class Foo. Every class, when loaded, is given an instance of class Class. That means that no matter who invokes method Foo.bar(), the lock will be on the static instance, and not on any specific instance of class Foo. I know this sounds confusing, but it has the same semantics as any other use of static: all statics (methods, variables, etc) are essentially global, interact with all other statics of the same class, and do not interact with non-static instance data. Whether a method is public or not makes no difference to the semantics of synchronized. (* Actually, there is a very small, technical difference between void bar() { synchronized (this) { ... } } and synchronized void bar() { ... }: the VM may be able to very slightly optimize the latter case, since the synchronization is marked in the method signature and not in code. However, this is not important in practice.)

Page 33: Java Interview

What does the 'synchronized' modifier for a class declaration do? I see decompilers generating the code and javac compiling it without difficulty. Example: public synchronized class HelloWorld {}synchronized is not a valid modifier for a class. According to the Java Language Specification (JLS 8.1.2, see Resources), public, abstract, and final are the only valid modifiers for a top-level class. Inner classes can also be private, protected, or static. Therefore, the compiler should reject the code in your example. In fact, this is a known bug, fixed in JDK 1.2. Out of curiosity, we checked to see if the synchronized modifier on a class had any effect in the generated code. We tried compiling a class with several different kinds of methods (abstract, final, static, and so on) with and without the synchronized keyword. The class files generated were exactly the same. It is also a bug for a decompiler, such as javap, to report classes as being synchronized. In fact, javap claims that every class is synchronized. This bug is also fixed in JDK 1.2. Documentation on these two bugs and others can be found in the Bug Parade on the Java Developer Connection Website.

sleep() and yield() are defined as static yes or no?yes

What is the meaning of calling a method or object "thread-safe?" Basically, calling a method "thread-safe" means that even if multiple threads try to access it simultaneously, nothing bad happens. Here "bad" usually means that due to race conditions, or deadlock, or other pitfalls, the object's state gets corrupted, or its methods produce unreliable results. A method usually acheives thread-safety by protecting access to shared resources. This usually translates to using the Java synchronized keyword to protect blocks of code that access instance variables, or other shared variables. For an object to be thread-safe, it must be possible for multiple threads to simultaneously access the same method, or multiple methods, in that object. Usually this is acheived by assuring that each method is thread-safe, but this doesn't always suffice, since methods can call each other in strange ways, leading to deadlock and other weirdness. It is very difficult to prove that an object is thread-safe. The main rule of thumb for making thread-safe objects is, "Make all the instance variables private, and all the public accessor methods synchronized." However, this is sometimes difficult to achieve in practice, due to exigencies of performance, architecture, or implementation. Accurate multithreaded programming is a true art, and very difficult to master. Read "Java Threads" by Oaks and Wong, and "Concurrent Programming in Java" by Lea, for inspiration in your quest to become a thread-safe programmer.

What is deadlock? How can I eliminate it? Is there a way in Java to check whether an object is locked? NoThread.getState method. When called on a thread, one of the following Thread.State values is returned: NEW RUNNABLE BLOCKED WAITING TIMED_WAITING TERMINATED

Page 34: Java Interview

Q.Why must classes be marked serializable in order to be written to an ObjectOutputStream? The decision to require that classes implement the java.io.Serializable interface was not made lightly. The design called for a balance between the needs of developers and the needs of the system to be able to provide a predictable and safe mechanism. The most difficult design constraint to satisify was the safety and security of Java classes. If classes were to be marked as being serializable, the design team worried that a developer, either out of forgetfulness, laziness, or ignorance might not declare a class as being Serializable and then make that class useless for RMI or for purposes of persistence. We worried that the requirement would place on a developer the burden of knowing how a class was to be used by others in the future, an essentially unknown condition. Indeed, our preliminary design, as reflected in the alpha API, concluded that the default case for a class ought to be that the objects in the class be serializable. We later changed our design only after security and correctness considerations convinced us that the default had to be that an object not be serialized. Security Restrictions: The first consideration that caused us to change the default behavior of objects had to do with security, in particular the privacy of fields declared to be private, package protected, or protected. The Java runtime restricts access to such fields for either read or write to a subset of the objects within the runtime. No such restriction can be made on an object once it has been serialized; the stream of bytes that are the result of object serialization can be read and altered by any object that has access to that stream. This allows any object access to the state of a serialized object, which can violate the privacy guarantees that users of the language expect. Furthermore, the bytes in the stream can be altered in arbitrary ways, allowing reconstruction of an object that was never created within the protections of a Java environment. There are cases in which the recreation of such an object could compromise not only the privacy guarantees expected by users of the Java environment, but also the integrity of the environment itself. These violations cannot be guarded against, since the whole idea of serialization is to allow an object to be converted into a form that can be moved outside of the Java environment (and therefore outside of the privacy and integrity guarantees of that environment) and then be brought back into the environment. Requiring objects to be declared Serializable does mean that the class designer must make an active decision to allow the possibility of such a breach in privacy or integrity. A developer who does not know about serialization should not be open to compromise because of this lack of knowledge. In addition, the developer who declares a class to be Serializable must only do so after giving some thought to the possible consequences of that declaration. Note that this sort of security problem is not one that can be dealt with by the mechanism of a security manager. Since serialization is intended to allow the transport of an object from one virtual machine to some other (either over space, as it is used in RMI, or over time, as when the stream is saved to a file), the mechanisms used for security need to be independent of the runtime environment of any particular virtual machine. We wanted to avoid as much as possible the problem of being able to serialize an object in one virtual machine and not being able to deserialize that object in some other virtual machine. Since

Page 35: Java Interview

the security manager is part of the runtime environment, using the security manager for serialization would have violated this requirement. Forcing a Conscious Decision: While security concerns were the first reason for considering the design change, a reason that we feel is at least as convincing is that serialization should only be added to a class after some design consideration. It is far too easy to design a class that falls apart under serialization and reconstruction. By requiring a class designer to declare support for the Serialization interface, we hoped that the designer would also give some thought to the process of serializing that class. Examples are easy to cite. Many classes deal with information that only makes sense in the context of the runtime in which the particular object exists; examples of such information include file handles, open socket connections, security information, etc. Such data can easily be dealt with by simply declaring the fields as transient, but such a declaration is only necessary if the object is going to be serialized. A novice (or forgetful, or hurried) programmer may neglect to mark fields as transient in much the same way he or she may neglect to mark the class as implementing the Serializable interface. Such a case should not lead to incorrect behavior; the way to avoid this is to not serialize objects that are not marked as implementing Serializable. Another example of this sort is the "simple" object that is the root of a graph which spans a large number of objects. Serializing such an object could result in serializing several others, since serialization works over an entire graph. Doing something like this should be a conscious decision, not one that happens by default. The need for this sort of thought was brought home to us when we were going through the base Java class libraries marking the system classes as Serializable (where appropriate). Originally, we thought that this would be a fairly simple process, and that most of the system classes could just be marked as implementing Serializable and then use the default implementation with no other changes. What we found was that this was far less often the case than we had suspected. In a large number of the classes, careful thought had to be given to whether or not a field should be marked as transient or whether it made sense to serialize the class at all. Of course, there is no way to guarantee that a programmer or class designer is actually going to think about these issues when marking a class as Serializable. However, by requiring the class to declare itself as implementing the Serializable interface, we do require that some thought be given by the programmer. Having serialization be the default state of an object would mean that lack of thought could cause bad effects in a program, something that the overall design of the Java programming environment has attempted to avoid.

If class A does not implement Serializable but a subclass B implements Serializable, will the fields of class A be serialized when B is serialized? Only the fields of Serializable objects are written out and restored. The object may be restored only if it has a no-arg constructor that will initialize the fields of non-serializable supertypes. If the subclass has access to the state of the superclass it can implement writeObject and readObject to save and restore that state.

Page 36: Java Interview

Why would you use a synchronized block vs. synchronized method? Synchronized blocks place locks for shorter periods than synchronized methods.

Q: What type of parameter passing does Java support?A: In Java the arguments are always passed by value . Q: Primitive data types are passed by reference or pass by value?A: Primitive data types are passed by value. Q: Objects are passed by value or by reference?A: Java only supports pass by value. With objects, the object reference itself is passed by value and so both the original reference and parameter copy both refer to the same object .

Q: What is serialization?A: Serialization is a mechanism by which you can save the state of an object by converting it to a byte stream.

Q: How do I serialize an object to a file?A: The class whose instances are to be serialized should implement an interface Serializable. Then you pass the instance to the ObjectOutputStream which is connected to a fileoutputstream. This will save the object to a file.

Q: Which methods of Serializable interface should I implement?A: The serializable interface is an empty interface, it does not contain any methods. So we do not implement any methods.

Q: How can I customize the seralization process? i.e. how can one have a control over the serialization process?A: Yes it is possible to have control over serialization process. The class should implement Externalizable interface. This interface contains two methods namely readExternal and writeExternal. You should implement these methods and write the logic for customizing the serialization process.

Q: What is the common usage of serialization?A: Whenever an object is to be sent over the network, objects need to be serialized. Moreover if the state of an object is to be saved, objects need to be serilazed.

Q: What is Externalizable interface?A: Externalizable is an interface which contains two methods readExternal and writeExternal. These methods give you a control over the serialization mechanism. Thus if your class implements this interface, you can customize the serialization process by implementing these methods. Q: What happens to the object references included in the object?A: The serialization mechanism generates an object graph for serialization. Thus it determines whether the included object references are serializable or not. This is a recursive process. Thus when an object is serialized, all the included objects are also serialized alongwith the original obect.

Q: What one should take care of while serializing the object?A: One should make sure that all the included objects are also serializable. If any of the objects is not serializable then it throws a NotSerializableException.

Page 37: Java Interview

Q: What happens to the static fields of a class during serialization? A: There are three exceptions in which serialization doesnot necessarily read and write to the stream. These are1. Serialization ignores static fields, because they are not part of ay particular state state.2. Base class fields are only hendled if the base class itself is serializable.3. Transient fields. What are wrapper classes?A: Java provides specialized classes corresponding to each of the primitive data types. These are called wrapper classes. They are e.g. Integer, Character, Double etc.

What if the main method is declared as private?A: The program compiles properly but at runtime it will give "Main method not public." message. Q: What if the static modifier is removed from the signature of the main method?A: Program compiles. But at runtime throws an error "NoSuchMethodError". Q: What if I write static public void instead of public static void?A: Program compiles and runs properly.

Q: What if I do not provide the String array as the argument to the method?A: Program compiles but throws a runtime error "NoSuchMethodError". Q: What is the first argument of the String array in main method? A: The String array is empty. It does not have any element. This is unlike C/C++ where the first element by default is the program name. Q: If I do not provide any arguments on the command line, then the String array of Main method will be empty of null? A: It is empty. But not null. Q: How can one prove that the array is not null but empty? A: Print args.length. It will print 0. That means it is empty. But if it would have been null then it would have thrown a NullPointerException on attempting to print args.length. Can we define private and protected modifiers for variables in interfaces? - No 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) What modifiers are allowed for methods in an Interface? - Only public and abstract modifiers are allowed for methods in interfaces. 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

Page 38: Java Interview

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 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). 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(). 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. How do I convert a numeric IP address like 192.18.97.39 into a hostname like java.sun.com?

String hostname = InetAddress.getByName(\”192.18.97.39\”).getHostName();Difference between JRE/JVM/JDK? 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. 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. Is null a keyword? - The null value is not a keyword.

Page 39: Java Interview

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. 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. 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. What are wrapped classes? - Wrapped classes are classes that allow primitive types to be accessed as objects. 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). 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. What is a native method? - A native method is a method that is implemented in a language other than Java. 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-to-right or right-to-left 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. 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. What is the range of the char type? - The range of the char type is 0 to 2^16 - 1.

Q: What environment variables do I need to set on my machine in order to be able to run Java programs? A: CLASSPATH and PATH are the two variables. Q: Can an application have multiple classes having main method?

Page 40: Java Interview

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: Do I need to import java.lang package any time? Why ? A: No. It is by default loaded internally by the JVM. Q: Can I import same package/class twice? Will the JVM load the package twice at runtime? A: One can import the same package or same class multiple times. Neither compiler nor JVM complains abt it. And the JVM will internally load the class only once no matter how many times you import the same class. Q: What are Checked and UnChecked Exception? A: A checked exception is some subclass of Exception (or Exception itself), excluding class RuntimeException and its subclasses.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 theexception or declare it in a throws clause. In fact, client programmers may not even know that the exception could be thrown. eg, StringIndexOutOfBoundsException thrown by String's charAt() method· Checked exceptions must be caught at compile time. Runtime exceptions do not need to be. Errors often cannot be.

Q: What is Overriding? A: When a class defines a method using the same name, return type, and arguments as a method in its superclass, the method in the class overrides the method in the superclass.When the method is invoked for an object of the class, it is the new definition of the method that is called, and not the method definition from superclass. Methods may be overridden to be more public, not more private.

Q: What are different types of inner classes? A: Nested top-level classes, Member classes, Local classes, Anonymous classes

Nested top-level classes- If you declare a class within a class and specify the static modifier, the compiler treats the class just like any other top-level class.Any class outside the declaring class accesses the nested class with the declaring class name acting similarly to a package. eg, outer.inner. Top-level inner classes implicitly have access only to static variables.There can also be inner interfaces. All of these are of the nested top-level variety.

Member classes - Member inner classes are just like other member methods and member variables and access to the member class is restricted, just like methods and variables. This means a public member class acts similarly to a nested top-level class. The primary difference between member classes and nested top-level classes is that member classes have access to the specific instance of the enclosing class.

Page 41: Java Interview

Local classes - Local classes are like local variables, specific to a block of code. Their visibility is only within the block of their declaration. In order for the class to be useful beyond the declaration block, it would need to implement amore publicly available interface.Because local classes are not members, the modifiers public, protected, private, and static are not usable.

Anonymous classes - Anonymous inner classes extend local inner classes one level further. As anonymous classes have no name, you cannot provide a constructor. Q: Why do we need wrapper classes? A: It is sometimes easier to deal with primitives as objects. Moreover most of the collection classes store objects and not primitive data types. And also the wrapper classes provide many utility methods also. Because of these resons we need wrapper classes. And since we create instances of these classes we can store them in any of the collection classes and pass them around as a collection. Also we can pass them around as method parameters where a method expects an object. Q: What are checked exceptions? A: Checked exception are those which the Java compiler forces you to catch. e.g. IOException are checked Exceptions.

Q: What are runtime exceptions? A: Runtime exceptions are those exceptions that are thrown at runtime because of either wrong input data or because of wrong business logic etc. These are not checked by the compiler at compile time.

Q: What is the difference between error and an exception? A: An error is an irrecoverable condition occurring at runtime. Such as OutOfMemory error. These JVM errors and you can not repair them at runtime. While exceptions are conditions that occur because of bad input etc. e.g. FileNotFoundException will be thrown if the specified file does not exist. Or a NullPointerException will take place if you try using a null reference. In most of the cases it is possible to recover from an exception (probably by giving user a feedback for entering proper values etc.). Q: How to create custom exceptions?A: Your class should extend class Exception, or some more specific type thereof. Q: If I want an object of my class to be thrown as an exception object, what should I do?A: The class should extend from Exception class. Or you can extend your class from some more precise exception type also. Q: If my class already extends from some other class what should I do if I want an instance of my class to be thrown as an exception object?A: One can not do anytihng in this scenarion. Because Java does not allow multiple inheritance and does not provide any exception interface as well.

Q: What happens to an unhandled exception?A: One can not do anytihng in this scenarion. Because Java does not allow multiple inheritance and does not provide any exception interface as well.

Page 42: Java Interview

Q: How does an exception permeate through the code?A: An unhandled exception moves up the method stack in search of a matching When an exception is thrown from a code which is wrapped in a try block followed by one or more catch blocks, a search is made for matching catch block. If a matching type is found then that block will be invoked. If a matching type is not found then the exception moves up the method stack and reaches the caller method. Same procedure is repeated if the caller method is included in a try catch block. This process continues until a catch block handling the appropriate type of exception is found. If it does not find such a block then finally the program terminates. Q: What are the different ways to handle exceptions?A: There are two ways to handle exceptions, 1. By wrapping the desired code in a try block followed by a catch block to catch the exceptions. and 2. List the desired exceptions in the throws clause of the method and let the caller of the method hadle those exceptions.

Q: Q: What is the basic difference between the 2 approaches to exception handling...1> try catch block and 2> specifying the candidate exceptions in the throws clause?When should you use which approach?A: In the first approach as a programmer of the method, you urself are dealing with the exception. This is fine if you are in a best position to decide should be done in case of an exception. Whereas if it is not the responsibility of the method to deal with it's own exceptions, then do not use this approach. In this case use the second approach. In the second approach we are forcing the caller of the method to catch the exceptions, that the method is likely to throw. This is often the approach library creators use. They list the exception in the throws clause and we must catch them. You will find the same approach throughout the java libraries we use. Q: Is it necessary that each try block must be followed by a catch block?A: It is not necessary that each try block must be followed by a catch block. It should be followed by either a catch block OR a finally block. And whatever exceptions are likely to be thrown should be declared in the throws clause of the method. Q: If I write return at the end of the try block, will the finally block still execute?A: Yes even if you write return as the last statement in the try block and no exception occurs, the finally block will execute. The finally block will execute and then the control return. Q: If I write System.exit (0); at the end of the try block, will the finally block still execute?A: No in this case the finally block will not execute because when you say System.exit (0); the control immediately goes out of the program, and thus finally never executes.Whats the difference between notify() and notifyAll()? - notify() is used to unblock one waiting thread; notifyAll() is used to unblock all of them. Using notify() is preferable (for efficiency) when only one blocked thread can benefit from the change (for example, when freeing a buffer back into a pool). notifyAll() is necessary (for correctness) if multiple threads should resume (for example, when

Page 43: Java Interview

releasing a “writer” lock on a file might permit all “readers” to resume). Why can’t I say just abs() or sin() instead of Math.abs() and Math.sin()? - The import statement does not bring methods into your local name space. It lets you abbreviate class names, but not get rid of them altogether. That’s just the way it works, you’ll get used to it. It’s really a lot safer this way. However, there is actually a little trick you can use in some cases that gets you what you want. If your top-level class doesn’t need to inherit from anything else, make it inherit from java.lang.Math. That does bring all the methods into your local name space. But you can’t use this trick in an applet, because you have to inherit from java.awt.Applet. And actually, you can’t use it on java.lang.Math at all, because Math is a “final” class which means it can’t be extended. Why are there no global variables in Java? - Global variables are considered bad form for a variety of reasons: Adding state variables breaks referential transparency (you no longer can understand a statement or expression on its own: you need to understand it in the context of the settings of the global variables), State variables lessen the cohesion of a program: you need to know more to understand how something works. A major point of Object-Oriented programming is to break up global state into more easily understood collections of local state, When you add one variable, you limit the use of your program to one instance. What you thought was global, someone else might think of as local: they may want to run two copies of your program at once. For these reasons, Java decided to ban global variables. What does it mean that a class or member is final? - A final class can no longer be subclassed. Mostly this is done for security reasons with basic classes like String and Integer. It also allows the compiler to make some optimizations, and makes thread safety a little easier to achieve. Methods may be declared final as well. This means they may not be overridden in a subclass. Fields can be declared final, too. However, this has a completely different meaning. A final field cannot be changed after it’s initialized, and it must include an initializer statement where it’s declared. For example, public final double c = 2.998; It’s also possible to make a static field final to get the effect of C++’s const statement or some uses of C’s #define, e.g. public static final double c = 2.998; What does it mean that a method or class is abstract? - An abstract class cannot be instantiated. Only its subclasses can be instantiated. You indicate that a class is abstract with the abstract keyword like this:

public abstract class Container extends Component {Abstract classes may contain abstract methods. A method declared abstract is not actually implemented in the current class. It exists only to be overridden in subclasses. It has no body. For example,

Page 44: Java Interview

public abstract float price();Abstract methods may only be included in abstract classes. However, an abstract class is not required to have any abstract methods, though most of them do. Each subclass of an abstract class must override the abstract methods of its superclasses or itself be declared abstract. What is a transient variable? - transient variable is a variable that may not be serialized. How are Observer and Observable used? - Objects that subclass the Observable class maintain a list of observers. When an Observable object is updated it invokes the update() method of each of its observers to notify the observers that it has changed state. The Observer interface is implemented by objects that observe Observable objects. 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. What state does a thread enter when it terminates its processing? - When a thread terminates its processing, it enters the dead state. 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. What is the difference between the >> and >>> operators? - The >> operator carries the sign bit when shifting right. The >>> zero-fills bits that have been shifted out. Is sizeof a keyword? - The sizeof operator is not a keyword. Does garbage collection guarantee that a program will not run out of memory? - Garbage collection does not guarantee that a program will not run out of memory. 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 Can an object’s finalize() method be invoked while it is reachable? - An object’s finalize() method cannot be invoked by the garbage collector while the object is still reachable. However, an object’s finalize() method may be invoked by other objects. What value does readLine() return when it has reached the end of a file? - The readLine() method returns null when it has reached the end of a file. Can a for statement loop indefinitely? - Yes, a for statement can loop indefinitely. For example, consider the following: for(;;) ; To what value is a variable of the String type automatically initialized? - The default value of an String type is null. What is a task’s priority and how is it used in scheduling? - A task’s priority is an integer value that identifies the relative order in which it should be executed with respect to other tasks. The scheduler attempts to schedule higher priority tasks before lower priority tasks.

Page 45: Java Interview

What is the range of the short type? - The range of the short type is -(2^15) to 2^15 - 1. What is the purpose of garbage collection? - The purpose of garbage collection is to identify and discard objects that are no longer needed by a program so that their resources may be reclaimed and reused. What do you understand by private, protected and public? - These are accessibility modifiers. Private is the most restrictive, while public is the least restrictive. There is no real difference between protected and the default type (also known as package protected) within the context of the same package, however the protected keyword allows visibility to a derived class in a different package. What is Downcasting ? - Downcasting is the casting from a general to a more specific type, i.e. casting down the hierarchy Can a method be overloaded based on different return type but same argument type ? - No, because the methods can be called without using their return type in which case there is ambiquity for the compiler What happens to a static var that is defined within a method of a class ? - Can’t do it. You’ll get a compilation error How many static init can you have ? - As many as you want, but the static initializers and class variable initializers are executed in textual order and may not refer to class variables declared in the class whose declarations appear textually after the use, even though these class variables are in scope. What is the difference amongst JVM Spec, JVM Implementation, JVM Runtime ? - The JVM spec is the blueprint for the JVM generated and owned by Sun. The JVM implementation is the actual implementation of the spec by a vendor and the JVM runtime is the actual running instance of a JVM implementation Describe what happens when an object is created in Java? - Several things happen in a particular order to ensure the object is constructed properly: Memory is allocated from heap to hold all instance variables and implementation-specific data of the object and its superclasses. Implemenation-specific data includes pointers to class and method data. The instance variables of the objects are initialized to their default values. The constructor for the most derived class is invoked. The first thing a constructor does is call the consctructor for its superclasses. This process continues until the constrcutor for java.lang.Object is called, as java.lang.Object is the base class for all objects in java. Before the body of the constructor is executed, all instance variable initializers and initialization blocks are executed. Then the body of the constructor is executed. Thus, the constructor for the base class completes first and constructor for the most derived class completes last.

Page 46: Java Interview

What does the “final” keyword mean in front of a variable? A method? A class? - FINAL for a variable: value is constant. FINAL for a method: cannot be overridden. FINAL for a class: cannot be derived What is the difference between instanceof and isInstance? - instanceof is used to check to see if an object can be cast into a specified type without throwing a cast class exception. isInstance() Determines if the specified Object is assignment-compatible with the object represented by this Class. This method is the dynamic equivalent of the Java language instanceof operator. The method returns true if the specified Object argument is non-null and can be cast to the reference type represented by this Class object without raising a ClassCastException. It returns false otherwise What is the difference between URL instance and URLConnection instance? A URL instance represents the location of a resource, and a URLConnection instance represents a link for accessing or communicating with the resource at the location. What are the two important TCP Socket classes? Socket and ServerSocket. ServerSocket is used for normal two-way socket communication. Socket class allows us to read and write through the sockets. getInputStream() and getOutputStream() are the two methods available in Socket class. What technologies are included in J2EE? The primary technologies in J2EE are: Enterprise JavaBeansTM (EJBsTM), JavaServer PagesTM (JSPsTM), Java Servlets, the Java Naming and Directory InterfaceTM (JNDITM), the Java Transaction API (JTA), CORBA, and the JDBCTM data access API. What is the Java Authentication and Authorization Service (JAAS) 1.0? - 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. JAAS is a Java programing language version of the standard Pluggable Authentication Module (PAM) framework that extends the Java 2 platform security architecture to support user-based authorization. What’s the difference between JNDI lookup(), list(), listBindings(), and search()? - lookup() attempts to find the specified object in the given context. I.e., it looks for a single, specific object and either finds it in the current context or it fails. list() attempts to return an enumeration of all of the NameClassPair’s of all of the objects in the current context. I.e., it’s a listing of all of the objects in the current context but only returns the object’s name and the name of the class to which the object belongs. listBindings() attempts to return an enumeration of the Binding’s of all of the objects in the current context. I.e., it’s a listing of all of the objects in the current context with the object’s name, its class name, and a reference to the object itself. search() attempts to return an enumeration of all of the objects matching a given set of search criteria. It can search across multiple contexts (or not). It can return whatever attributes of the

Page 47: Java Interview

objects that you desire. It’s by far the most complex and powerful of these options but is also the most expensive. Components of JNDI - Naming Interface- The naming interface organizes information hierarchically and maps human-friendly names to addresses or objects that are machine-friendly. It allows access to named objects through multiple namespaces. Directory Interface - JNDI includes a directory service interface that provides access to directory objects, which can contain attributes, thereby providing attribute-based searching and schema support. Service Provider Interface - JNDI comes with the SPI, which supports the protocols provided by third parties. What is the Max amount of information that can be saved in a Session Object? - 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. Must my bean-managed persistence mechanism use the WebLogic JTS driver? - BEA recommend that you use the TxDataSource for bean-managed persistence. Do EJBs have to be homogeneously deployed across a cluster? Why? - Yes. Beginning with WebLogic Server version 6.0, EJBs must be homogeneously deployed across a cluster for the following reasons:

To keep clustering EJBs simple To avoid cross server calls which results in more efficiency. If EJBs are not deployed on all servers, cross server calls are much more likely. To ensure that every EJB is available locally To ensure that all classes are loaded in an undeployable way

Every server must have access to each EJB’s classes so that it can be bound into the local JNDI tree. If only a subset of the servers deploys the bean, the other servers will have to load the bean’s classes in their respective system classpaths which makes it impossible to undeploy the beans.Is an XSLT processor bundled in WebLogic Server? - Yes, an XSLT processor, based on Apache’s Xalan 2.0.1 processor, in WebLogic Server 6.1. I plugged in a version of Apache Xalan that I downloaded from the Apache Web site, and now I get errors when I try to transform documents. What is the problem? - You must ensure that the version of Apache Xalan you download from the Apache Web site is compatible with Apache Xerces version 1.3.1. Because you cannot plug in a

Page 48: Java Interview

different version of Apache Xerces , the only version of Apache Xerces that is compatible with WebLogic Server 6.1 is 1.3.1. The built-in parser (based on version 1.3.1 of Apache Xerces) and transformer (based on version 2.0.1 of Apache Xalan) have been modified by BEA to be compatible with each other. How do I increase WebLogic Server memory? - Increase the allocation of Java heap memory for WebLogic Server. (Set the minimum and the maximum to the same size.) Start WebLogic Server with the -ms32m option to increase the allocation, as in this example:

$ java ... -ms32m -mx32m ...This allocates 32 megabytes of Java heap memory to WebLogic Server, which improves performance and allows WebLogic Server to handle more simultaneous connections. You can increase this value if necessary. What causes Java.io exceptions in the log file of WebLogic Server? - You may see messages like these in the log file: (Windows NT)

java.io.IOException Connection Reset by Peerjava.io.EOFException Connection Reset by Peer

(Solaris)java.io.Exception: Broken pipe

These messages occur when you are using servlets. A client initiates an HTTP request, and then performs a series of actions on the browser:Click Stop or enter equivalent command or keystrokes Click Refresh or enter equivalent command or keystrokes Send a new HTTP request.The messages indicate that WebLogic Server has detected and recovered from an interrupted HTTP request. What is the function of T3 in WebLogic Server? - T3 provides a framework for WebLogic Server messages that support for enhancements. These enhancements include abbreviations and features, such as object replacement, that work in the context of WebLogic Server clusters and HTTP and other product tunneling. T3 predates Java Object Serialization and RMI, while closely tracking and leveraging these specifications. T3 is a superset of Java Object. Serialization or RMI; anything you can do in Java Object Serialization and RMI can be done over T3. T3 is mandated between WebLogic Servers and between programmatic clients and a WebLogic Server cluster. HTTP and IIOP are optional protocols that can be used to communicate between other processes and WebLogic Server. It depends on what you want to do. For example, when you want to communicate between a browser and WebLogic Server-use HTTP, or an ORB and WebLogic Server-IIOP. What are the enhancements in EJB 2.0 specification with respect to Asynchronous communication? - EJB 2.0 mandates integration between JMS and EJB. We have specified the integration of

Page 49: Java Interview

Enterprise JavaBeans with the Java Message Service, and have introduced message-driven beans. A message-driven bean is a stateless component that is invoked by the container as a result of the arrival of a JMS message. The goal of the message-driven bean model is to make developing an enterprise bean that is asynchronously invoked to handle the processing of incoming JMS messages as simple as developing the same functionality in any other JMS MessageListener. What are the enhancements in EJB 2.0 with respect to CMP? - EJB 2.0 extends CMP to include far more robust modeling capability, with support for declarative management of relationships between entity EJBs. Developers no longer need to re-establish relationships between the various beans that make up their application — the container will restore the connections automatically as beans are loaded, allowing bean developers to navigate between beans much as they would between any standard Java objects.EJB 2.0 also introduces for the first time a portable query language, based on the abstract schema, not on the more complex database schema. This provides a database and vendor-independent way to find entity beans at run time, based on a wide variety of search criteria. Can you briefly describe local interfaces? - EJB was originally designed around remote invocation using the Java Remote Method Invocation (RMI) mechanism, and later extended to support to standard CORBA transport for these calls using RMI/IIOP. This design allowed for maximum flexibility in developing applications without consideration for the deployment scenario, and was a strong feature in support of a goal of component reuse in J2EE. Many developers are using EJBs locally - that is, some or all of their EJB calls are between beans in a single container. With this feedback in mind, the EJB 2.0 expert group has created a local interface mechanism. The local interface may be defined for a bean during development, to allow streamlined calls to the bean if a caller is in the same container. This does not involve the overhead involved with RMI like marshalling etc. This facility will thus improve the performance of applications in which co-location is planned. Local interfaces also provide the foundation for container-managed relationships among entity beans with container-managed persistence. What are the special design care that must be taken when you work with local interfaces? - It is important to understand that the calling semantics of local interfaces are different from those of remote interfaces. For example, remote interfaces pass parameters using call-by-value semantics, while local interfaces use call-by-reference. This means that in order to use local interfaces safely, application developers need to carefully consider potential deployment scenarios up front, then decide which interfaces can be local and which remote, and finally, develop the application code with these choices in mind.

Page 50: Java Interview

While EJB 2.0 local interfaces are extremely useful in some situations, the long-term costs of these choices, especially when changing requirements and component reuse are taken into account, need to be factored into the design decision. What happens if remove( ) is never invoked on a session bean? - In case of a stateless session bean it may not matter if we call or not as in both cases nothing is done. The number of beans in cache is managed by the container. In case of stateful session bean, the bean may be kept in cache till either the session times out, in which case the bean is removed or when there is a requirement for memory in which case the data is cached and the bean is sent to free pool. What is the difference between creating a distributed application using RMI and using a EJB architecture? - It is possible to create the same application using RMI and EJB. But in case of EJB the container provides the requisite services to the component if we use the proper syntax. It thus helps in easier development and lesser error and use of proven code and methodology. But the investment on application server is mandatory in that case. But this investment is warranted because it results in less complex and maintainable code to the client, which is what the end client wants. Almost all the leading application servers provide load balancing and performance tuning techniques. In case of RMI we have to code the services and include in the program the way to invoke these services. Why would a client application use JTA transactions? - One possible example would be a scenario in which a client needs to employ two (or more) session beans, where each session bean is deployed on a different EJB server and each bean performs operations against external resources (for example, a database) and/or is managing one or more entity beans. In this scenario, the client’s logic could required an all-or-nothing guarantee for the operations performed by the session beans; hence, the session bean usage could be bundled together with a JTA UserTransaction object. In the previous scenario, however, the client application developer should address the question of whether or not it would be better to encapsulate these operations in yet another session bean, and allow the session bean to handle the transactions via the EJB container. In general, lightweight clients are easier to maintain than heavyweight clients. Also, EJB environments are ideally suited for transaction management. Context c = new InitialContext(); UserTransaction ut = (UserTransaction)c.lookup(\”java:comp/UserTransaction\”);ut.begin();

// perform multiple operations...ut.commit() ...Can the bean class implement the EJBObject class directly? If not why? - It is better not to do it will make the Bean class a remote

Page 51: Java Interview

object and its methods can be accessed without the containers? security, and transaction implementations if our code by mistake passed it in one of its parameters. Its just a good design practice. What does isIdentical() method return in case of different type of beans? - Stateless - true always. Stateful - depends whether the references point to the same session object. Entity - Depends whether the primary key is the same and the home is same. How should you type cast a remote object? Why? - A client program that is intended to be interoperable with all compliant EJB Container implementations must use the javax.rmi.PortableRemoteObject.narrow(…) method to perform type-narrowing of the client-side representations of the remote home and remote interfaces. Programs using the cast operator for narrowing the remote and remote home interfaces are likely to fail if the Container implementation uses RMI-IIOP as the underlying communication transport. What should you do in a passive method? - You try to make all nontransient variables, which are not one of the following to null. For the given list the container takes care of serializing and restoring the object when activated. Serializable objects, null, UserTransaction, SessionContext, JNDI contexts in the beans context, reference to other beans, references to connection pools.

Jakarta struts questionsWhat is Jakarta Struts Framework? - Jakarta Struts is open source implementation of MVC (Model-View-Controller) pattern for the development of web based applications. Jakarta Struts is robust architecture and can be used for the development of application of any size. Struts framework makes it much easier to design scalable, reliable Web applications with Java. What is ActionServlet? - The class org.apache.struts.action.ActionServlet is the called the ActionServlet. In the 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. How you will make available any Message Resources Definitions file to the Struts Framework Environment? - Message Resources Definitions file are simple .properties files and these files contains the messages that can be used in the struts project. Message Resources Definitions files can be added to the struts-config.xml file through <message-resources /> tag.Example:<message-resources parameter=”MessageResources” />      What is 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

Page 52: Java Interview

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 ActionForward which is used by the Struts Framework to forward the request to the file as per the value of the returned ActionForward object.    Write code of any Action Class? - Here is the code of Action Class that returns the ActionForward object. import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.struts.action.Action; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping;

public class TestAction extends Action{ public ActionForward execute( ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception

{ return mapping.findForward(\”testAction\”);}

}What is ActionForm? - An ActionForm is a JavaBean that extends org.apache.struts.action.ActionForm. ActionForm maintains the session state for web application and the ActionForm object is automatically populated on the server side with data entered from a form on the client side.   What is Struts Validator Framework? - 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. Server side validation of form can be accomplished by sub classing your From Bean with DynaValidatorForm class. The Validator framework was developed by David Winterfeldt as third-party add-on to Struts. Now the Validator framework is a part of Jakarta Commons project and it can be used with or without Struts. The Validator framework comes integrated with the Struts Framework and

Page 53: Java Interview

can be used without doing any extra settings.    Give the Details of XML files used in Validator Framework? - The Validator Framework uses two XML configuration files validator-rules.xml and validation.xml. The validator-rules.xml defines the standard validation routines, these are reusable and used in validation.xml. to define the form specific validations. The validation.xml defines the validations applied to a form bean. How you will display validation fail errors on jsp page? - The following tag displays all the errors:<html:errors/>   How you will enable front-end validation based on the xml in validation.xml? - The <html:javascript> tag to allow front-end validation based on the xml in validation.xml. For  example the code: <html:javascript formName=”logonForm” dynamicJavascript=”true” staticJavascript=”true” /> generates the client side java script for the form “logonForm” as defined in the validation.xml file. The <html:javascript> when added in the jsp file generates the client site validation script.

JSP Inteview Questions:Q: What is a Declaration? A: A declaration declares one or more variables or methods for use later in the JSP source file. A declaration must contain at least one complete declarative statement. You can declare any number of variables or methods within one declaration tag, as long as they are separated by semicolons. The declaration must be valid in the scripting language used in the JSP file. <%! somedeclarations %><%! int i = 0; %><%! int a, b, c; %> Q: What is a Scriptlet? A: A scriptlet can contain any number of language statements, variable or method declarations, or expressions that are valid in the page scripting language.Within scriptlet tags, you can 1.Declare variables or methods to use later in the file (see also Declaration).2.Write expressions valid in the page scripting language (see also Expression). 3.Use any of the JSP implicit objects or any object declared with a <jsp:useBean> tag. You must write plain text, HTML-encoded text, or other JSP tags outside the scriptlet. Scriptlets are executed at request time, when the JSP engine processes the client request. If the scriptlet produces output, the output is stored in the out object, from which you can display it.

Q: What are implicit objects? List them? A: Certain objects that are available for the use in JSP documents without being declared first. These objects are parsed by the JSP engine and inserted into the generated servlet. The implicit objects re listed below

Page 54: Java Interview

request response pageContext session application out config page exception Q: Difference between forward and sendRedirect? A: When you invoke a forward request, the request is sent to another resource on the server, without the client being informed that a different resource is going to process the request. This process occurs completly with in the web container. When a sendRedirtect method is invoked, it causes the web container to return to the browser indicating that a new URL should be requested. Because the browser issues a completly new request any object that are stored as request attributes before the redirect occurs will be lost. This extra round trip a redirect is slower than forward.

Q: What are the different scope valiues for the <jsp:useBean>?A: The different scope values for <jsp:useBean> are 1. page2. request3.session4.application

Q: Explain the life-cycle mehtods in JSP? A: THe generated servlet class for a JSP page implements the HttpJspPage interface of the javax.servlet.jsp package. Hte HttpJspPage interface extends the JspPage interface which inturn extends the Servlet interface of the javax.servlet package. the generated servlet class thus implements all the methods of the these three interfaces. The JspPage interface declares only two mehtods - jspInit() and jspDestroy() that must be implemented by all JSP pages regardless of the client-server protocol. However the JSP specification has provided the HttpJspPage interfaec specifically for the JSp pages serving HTTP requests. This interface declares one method _jspService(). The jspInit()- The container calls the jspInit() to initialize te servlet instance.It is called before any other method, and is called only once for a servlet instance.The _jspservice()- The container calls the _jspservice() for each request, passing it the request and the response objects.The jspDestroy()- The container calls this when it decides take the instance out of service. It is the last method called n the servlet instance. Whats Difference between JSP:include action and include directiveThere are two mechanisms for including another Web resource in a JSP page: the include directive and the jsp:include element. The include directive is processed when the JSP page is translated into a servlet class. The effect of the directive is to insert the text contained in another file--either static content or another JSP page--in the including JSP page. You would probably use the include directive to include banner content, copyright information, or any chunk of content that you might want to reuse in another page. The syntax for the include directive is as follows: <%@ include file="filename" %>The jsp:include element is processed when a JSP page is executed. The include action allows you to include either a static or dynamic resource in a JSP file. The results of

Page 55: Java Interview

including static and dynamic resources are quite different. If the resource is static, its content is inserted into the calling JSP file. If the resource is dynamic, the request is sent to the included resource, the included page is executed, and then the result is included in the response from the calling JSP page. The syntax for the jsp:include element is as follows: <jsp:include page="includedPage" />

Q: How can I implement a thread-safe JSP page? What are the advantages and Disadvantages of using it? A: You can make your JSPs thread-safe by having them implement the SingleThreadModel interface. This is done by adding the directive <%@ page isThreadSafe="false" %> within your JSP page. With this, instead of a single instance of the servlet generated for your JSP page loaded in memory, you will have N instances of the servlet loaded and initialized, with the service method of each instance effectively synchronized. You can typically control the number of instances (N) that are instantiated for all servlets implementing SingleThreadModel through the admin screen for your JSP engine. More importantly, avoid using the tag for variables. If you do use this tag, then you should set isThreadSafe to true, as mentioned above. Otherwise, all requests to that page will access those variables, causing a nasty race condition. SingleThreadModel is not recommended for normal use. There are many pitfalls, including the example above of not being able to use <%! %>. You should try really hard to make them thread-safe the old fashioned way: by making them thread-safe . Q:What's a better approach for enabling thread-safe servlets and JSPs? SingleThreadModel Interface or Synchronization?A:Although the SingleThreadModel technique is easy to use, and works well for low volume sites, it does not scale well. If you anticipate your users to increase in the future, you may be better off implementing explicit synchronization for your shared data. The key however, is to effectively minimize the amount of code that is synchronzied so that you take maximum advantage of multithreading. Also, note that SingleThreadModel is pretty resource intensive from the server\'s perspective. The most serious issue however is when the number of concurrent requests exhaust the servlet instance pool. In that case, all the unserviced requests are queued until something becomes free - which results in poor performance. Since the usage is non-deterministic, it may not help much even if you did add more memory and increased the size of the instance pool.

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

How do you pass an InitParameter to a JSP? The JspPage interface defines the jspInit() and jspDestroy() method which the page writer can use in their pages and are invoked in much the same manner as the init() and destory() methods of a servlet. The example page below enumerates through all the parameters and prints them to the console.

<%@ page import="java.util.*" %><%!ServletConfig cfg =null;public void jspInit(){ServletConfig cfg=getServletConfig();for (Enumeration e=cfg.getInitParameterNames(); e.hasMoreElements();) {String name=(String)e.nextElement();String value = cfg.getInitParameter(name);

Page 56: Java Interview

System.out.println(name+"="+value);}}%>

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

<%@ page import="javax.naming.*, javax.rmi.PortableRemoteObject, foo.AccountHome, foo.Account" %>

<%!//declare a "global" reference to an instance of the home interface of the

session beanAccountHome accHome=null;public void jspInit() {//obtain an instance of the home interfaceInitialContext cntxt = new InitialContext( );Object ref= cntxt.lookup("java:comp/env/ejb/AccountEJB");accHome =

(AccountHome)PortableRemoteObject.narrow(ref,AccountHome.class);}%><%//instantiate the session beanAccount acct = accHome.create();//invoke the remote methodsacct.doWhatever(...);// etc etc...%>

Servlet InterView QuestionsExplain the life cycle methods of a Servlet.A: The javax.servlet.Servlet interface defines the three methods known as life-cycle method.public void init(ServletConfig config) throws ServletExceptionpublic void service( ServletRequest req, ServletResponse res) throws ServletException, IOExceptionpublic void destroy()First the servlet is constructed, then initialized wih the init() method.Any request from client are 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() methid, then garbaged collected and finalized.

What is the difference between using getSession(true) and getSession(false) methods? getSession(true) - This method will check whether already a session is existing for the user. If a session is existing, it will return that session object, Otherwise it will create new session object and return taht object. getSession(false) - This method will check existence of session. If session exists, then it returns the reference of that session object, if not, this methods will return null. Q: What is the difference between the getRequestDispatcher(String path) method of javax.servlet.ServletRequest interface and javax.servlet.ServletContext interface?

Page 57: Java Interview

A: The getRequestDispatcher(String path) method of javax.servlet.ServletRequest interface accepts parameter the path to the resource to be included or forwarded to, which can be relative to the request of the calling servlet. If the path begins with a "/" it is interpreted as relative to the current context root.

The getRequestDispatcher(String path) method of javax.servlet.ServletContext interface cannot accepts relative paths. All path must sart with a "/" and are interpreted as relative to curent context root.

Q: Explain the directory structure of a web application.A: The directory structure of a web application consists of two parts. A private directory called WEB-INFA public resource directory which contains public resource folder.WEB-INF folder consists of 1. web.xml2. classes directory3. lib directory

Q: What are the common mechanisms used for session tracking?A: Method 1) By URL rewriting Method 2) Using Session objectGetting Session form HttpServletRequest object HttpSession session = request.getSession(true);Get a Value from the session session.getValue(session.getId()); Adding values to sessioncart = new Cart();session.putValue(session.getId(), cart); At the end of the session, we can inactivate the session by using the following commandsession.invalidate();Method 3) Using cookiesMethod 4) Using hidden fields

How Can You invoke other web resources (or other servelt / jsp ) ? Servelt can invoke other Web resources in two ways: indirect and direct. Indirect Way : Servlet will return the resultant HTML to the browser which will point to another Servlet (Web resource)Direct Way : We can call another Web resource (Servelt / Jsp) from Servelt program itself, by using RequestDispatcher object.You can get this object using getRequestDispatcher("URL") method. You can get this object from either a request or a Context.Example : RequestDispatcher dispatcher = request.getRequestDispatcher("/jspsample.jsp");if (dispatcher != null)dispatcher.forward(request, response);

Q: Explain ServletContext.A: ServletContext interface is a window for a servlet to view it's environment. A servlet can use this interface to get information such as initialization parameters for the web applicationor servlet container's version. Every web application has one and only one ServletContext and is accessible to all active resource of that application.

Q: What is preinitialization of a servlet?

Page 58: Java Interview

A: A container doesnot initialize the servlets ass soon as it starts up, it initializes a servlet when it receives a request for that servlet first time. This is called lazy loading. The servlet specification defines the <load-on-startup> element, which can be specified in the deployment descriptor to make the servlet container load and initialize the servlet as soon as it starts up. The process of loading a servlet before any request comes in is called preloading or preinitializing a servlet.

Q: What is the difference between Difference between doGet() and doPost()?A: A doGet() method is limited with 2k of data to be sent, and doPost() method doesn't have this limitation. A request string for doGet() looks like the following: http://www.allapplabs.com/svt1?p1=v1&p2=v2&...&pN=vNdoPost() method call doesn't need a long text tail after a servlet name in a request. All parameters are stored in a request itself, not in a request string, and it's impossible to guess the data transmitted to a servlet only looking at a request string.

Q: What is the difference between HttpServlet and GenericServlet? A: A GenericServlet has a service() method aimed to handle requests. HttpServlet extends GenericServlet and adds support for doGet(), doPost(), doHead() methods (HTTP 1.0) plus doPut(), doOptions(), doDelete(), doTrace() methods (HTTP 1.1). Both these classes are abstract. Q: What is the difference between ServletContext and ServletConfig? A: ServletContext: Defines a set of methods that a servlet uses to communicate with its servlet container, for example, to get the MIME type of a file, dispatch requests, or write to a log file.The ServletContext object is contained within the ServletConfig object, which the Web server provides the servlet when the servlet is initialized ServletConfig: The object created after a servlet is instantiated and its default constructor is read. It is created to pass initialization information to the servlet.

Java database interview questionsHow do you call a Stored Procedure from JDBC? The first step is to create a CallableStatement object. As with Statement and PreparedStatement objects, this is done with an open Connection object. A CallableStatement object contains a call to a stored procedure.

CallableStatement cs =con.prepareCall("{call SHOW_SUPPLIERS}");

ResultSet rs = cs.executeQuery();Is the JDBC-ODBC Bridge multi-threaded? – No. The JDBC-ODBC Bridge does not support concurrent access from different threads. The JDBC-ODBC Bridge uses synchronized methods to serialize all of the calls that it makes to ODBC. Multi-threaded Java programs may use the Bridge, but they won’t get the advantages of multi-threading. Does the JDBC-ODBC Bridge support multiple concurrent open statements per connection? - No. You can open only one Statement object per connection when you are using the JDBC-ODBC Bridge. What is cold backup, hot backup, warm backup recovery? Cold backup (All these files must be backed up at the same time, before the databaseis restarted). Hot backup (official name is ‘online backup’) is a backup taken of each tablespace while the database is running and is being accessed by the users. When we will Denormalize data? - Data denormalization is reverse procedure, carried out purely for reasons of improving performance. It maybe efficient for a high-throughput system to replicate data for certain data.

Page 59: Java Interview

What is the advantage of using PreparedStatement? If we are using PreparedStatement the execution time will be less. The PreparedStatement object contains not just an SQL statement, but the SQL statement that has been precompiled. This means that when the PreparedStatement is executed,the RDBMS can just run the PreparedStatement’s Sql statement without having to compile it first. What is a “dirty read”? Quite often in database processing, we come across the situation wherein one transaction can change a value, and a second transaction can read this value before the original change has been committed or rolled back. This is known as a dirty read scenario because there is always the possibility that the first transaction may rollback the change, resulting in the second transaction having read an invalid value. While you can easily command a database to disallow dirty reads, this usually degrades the performance of your application due to the increased locking overhead. Disallowing dirty reads also leads to decreased system concurrency.

What is Metadata and why should I use it? - Metadata (’data about data’) is information about one of two things: Database information (java.sql.DatabaseMetaData), or Information about a specific ResultSet (java.sql.ResultSetMetaData). Use DatabaseMetaData to find information about your database, such as its capabilities and structure. Use ResultSetMetaData to find information about the results of an SQL query, such as size and types of columns

Different types of Transaction Isolation Levels? The isolation level describes the degree to which the data being updated is visible to other transactions. This is important when two transactions are trying to read the same row of a table. Imagine two transactions: A and B. Here three types of inconsistencies can occur: Dirty-read: A has changed a row, but has not committed the changes. B reads the uncommitted data but his view of the data may be wrong if A rolls back his changes and updates his own changes to the database.Non-repeatable read: B performs a read, but A modifies or deletes that data later. If B reads the same row again, he will get different data. Phantoms: A does a query on a set of rows to perform an operation. B modifies the table such that a query of A would have given a different result. The table may be inconsistent.TRANSACTION_READ_UNCOMMITTED : DIRTY READS, NON-REPEATABLE READ AND PHANTOMS CAN OCCUR.TRANSACTION_READ_COMMITTED : DIRTY READS ARE PREVENTED, NON-REPEATABLE READ AND PHANTOMS CAN OCCUR.TRANSACTION_REPEATABLE_READ : DIRTY READS , NON-REPEATABLE READ ARE PREVENTED AND PHANTOMS CAN OCCUR.TRANSACTION_SERIALIZABLE : DIRTY READS, NON-REPEATABLE READ AND PHANTOMS ARE PREVENTED.

What is 2 phase commit? A 2-phase commit is an algorithm used to ensure the integrity of a committing transaction. In Phase 1, the transaction coordinator contacts potential participants in the transaction. The participants all agree to make the results of the transaction permanent but do not do so immediately. The participants log information to disk to ensure they can complete In phase 2 f all the participants agree to commit, the coordinator logs that agreement and the outcome is decided. The recording of this agreement in the log ends in Phase 2, the coordinator informs each participant of the decision, and they permanently update their resources.

Page 60: Java Interview

How do you handle your own transaction ? Connection Object has a method called setAutocommit(Boolean istrue)- Default is true. Set the Parameter to false , and begin your transaction

What is the normal procedure followed by a java client to access the db.? The database connection is created in 3 steps: Find a proper database URLLoad the database driver Ask the Java DriverManager class to open a connection to your databaseIn java code, the steps are realized in code as follows:

Create a properly formatted JDBR URL for your database. (See FAQ on JDBC URL for more information). A JDBC URL has the formjdbc:someSubProtocol://myDatabaseServer/theDatabaseName

Class.forName(”my.database.driver”); Connection conn = DriverManager.getConnection(”a.JDBC.URL”, “databaseLogin”,”databasePassword”);What is a data source? - A DataSource class brings another level of abstraction than directly using a connection object. Data source can be referenced by JNDI. Data Source may point to RDBMS, file System , any DBMS etc.

What are collection pools? What are the advantages? A connection pool is a cache of database connections that is maintained in memory, so that the connections may be reused

How do you get Column names only for a table (SQL Server)? Write the Query. -

select name from syscolumnswhere id=(select id from sysobjects where name='user_hdr')order by colid --user_hdr is the table name

Java Web development interview questionsCan 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. How can a servlet refresh automatically if some new data has entered the database? - You can use a client-side Refresh or Server Push. 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. 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.

Page 61: Java Interview

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

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

}}

How many JSP scripting elements are there and what are they? - There are three scripting language elements: declarations, scriptlets, expressions. In the Servlet 2.4 specification SingleThreadModel has been deprecated, 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. 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 pre-compiled and saves the database the effort of parsing and compiling sql statements everytime a query is run. Each database has its 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 3-tier/n-tier architecture it was pretty common for stored

Page 62: Java Interview

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. 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. 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. 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. 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 <%@ page isThreadSafe=”false” % > within your JSP page.

EJB interview questionsIs is possible for an EJB client to marshal an object of class java.lang.Class to an EJB? - Technically yes, spec. compliant NO! - The enterprise bean must not attempt to query a class to obtain information about the declared members that are not otherwise accessible to the enterprise bean because of the security rules of the Java language. Is it legal to have static initializer blocks in EJB? - Although technically it is legal, static initializer blocks are used to execute some piece of code before executing any constructor or method while instantiating a class. Static initializer blocks are also typically used to initialize static fields - which may be illegal in EJB if they are read/write - In EJB this can be achieved by including the code in either the ejbCreate(), setSessionContext() or setEntityContext() methods. Is it possible to stop the execution of a method before completion in a SessionBean? - Stopping the execution of a method inside a Session Bean is not possible without writing code inside the Session Bean. This is because you are not allowed to access Threads inside an EJB. What is the default transaction attribute for an EJB? - There is no default transaction attribute for an EJB. Section 11.5 of EJB v1.1 spec says that the deployer must specify a value for the transaction attribute for those methods having container managed transaction. In WebLogic, the default transaction attribute for EJB is SUPPORTS.

Page 63: Java Interview

What is the difference between session and entity beans? When should I use one or the other? - An entity bean represents persistent global data from the database; a session bean represents transient user-specific data that will die when the user disconnects (ends his session). Generally, the session beans implement business methods (e.g. Bank.transferFunds) that call entity beans (e.g. Account.deposit, Account.withdraw) Is there any default cache management system with Entity beans ? In other words whether a cache of the data in database will be maintained in EJB ? - Caching data from a database inside the Application Server are what Entity EJB’s are used for.The ejbLoad() and ejbStore() methods are used to synchronize the Entity Bean state with the persistent storage(database). Transactions also play an important role in this scenario. If data is removed from the database, via an external application - your Entity Bean can still be “alive” the EJB container. When the transaction commits, ejbStore() is called and the row will not be found, and the transaction rolled back. Why is ejbFindByPrimaryKey mandatory? - An Entity Bean represents persistent data that is stored outside of the EJB Container/Server. The ejbFindByPrimaryKey is a method used to locate and load an Entity Bean into the container, similar to a SELECT statement in SQL. By making this method mandatory, the client programmer can be assured that if they have the primary key of the Entity Bean, then they can retrieve the bean without having to create a new bean each time - which would mean creating duplications of persistent data and break the integrity of EJB. Why do we have a remove method in both EJBHome and EJBObject? - With the EJBHome version of the remove, you are able to delete an entity bean without first instantiating it (you can provide a PrimaryKey object as a parameter to the remove method). The home version only works for entity beans. On the other hand, the Remote interface version works on an entity bean that you have already instantiated. In addition, the remote version also works on session beans (stateless and stateful) to inform the container of your loss of interest in this bean. How can I call one EJB from inside of another EJB? - EJBs can be clients of other EJBs. It just works. Use JNDI to locate the Home Interface of the other bean, then acquire an instance reference, and so forth. What is the difference between a Server, a Container, and a Connector? - An EJB server is an application, usually a product such as BEA WebLogic, that provides (or should provide) for concurrent client connections and manages system resources such as threads, processes, memory, database connections, network connections, etc. An EJB container runs inside (or within) an EJB server, and provides deployed EJB beans with transaction and security management, etc.

Page 64: Java Interview

The EJB container insulates an EJB bean from the specifics of an underlying EJB server by providing a simple, standard API between the EJB bean and its container. A Connector provides the ability for any Enterprise Information System (EIS) to plug into any EJB server which supports the Connector architecture. See Sun’s J2EE Connectors for more in-depth information on Connectors. How is persistence implemented in enterprise beans? - Persistence in EJB is taken care of in two ways, depending on how you implement your beans: container managed persistence (CMP) or bean managed persistence (BMP) For CMP, the EJB container which your beans run under takes care of the persistence of the fields you have declared to be persisted with the database - this declaration is in the deployment descriptor. So, anytime you modify a field in a CMP bean, as soon as the method you have executed is finished, the new data is persisted to the database by the container. For BMP, the EJB bean developer is responsible for defining the persistence routines in the proper places in the bean, for instance, the ejbCreate(), ejbStore(), ejbRemove() methods would be developed by the bean developer to make calls to the database. The container is responsible, in BMP, to call the appropriate method on the bean. So, if the bean is being looked up, when the create() method is called on the Home interface, then the container is responsible for calling the ejbCreate() method in the bean, which should have functionality inside for going to the database and looking up the data. What is an EJB Context? - EJBContext is an interface that is implemented by the container, and it is also a part of the bean-container contract. Entity beans use a subclass of EJBContext called EntityContext. Session beans use a subclass called SessionContext. These EJBContext objects provide the bean class with information about its container, the client using the bean and the bean itself. They also provide other functions. See the API docs and the spec for more details. Is method overloading allowed in EJB? - Yes you can overload methods Should synchronization primitives be used on bean methods? - No. The EJB specification specifically states that the enterprise bean is not allowed to use thread primitives. The container is responsible for managing concurrent access to beans at runtime. Are we allowed to change the transaction isolation property in middle of a transaction? - No. You cannot change the transaction isolation level in the middle of transaction. For Entity Beans, What happens to an instance field not mapped to any persistent storage, when the bean is passivated? - The specification infers that the container never serializes an instance of an Entity bean (unlike stateful session beans). Thus passivation simply involves moving the bean from the “ready” to the “pooled” bin. So what happens to the contents of an instance

Page 65: Java Interview

variable is controlled by the programmer. Remember that when an entity bean is passivated the instance gets logically disassociated from it’s remote object. Be careful here, as the functionality of passivation/activation for Stateless Session, Stateful Session and Entity beans is completely different. For entity beans the ejbPassivate method notifies the entity bean that it is being disassociated with a particular entity prior to reuse or for dereference. What is a Message Driven Bean, what functions does a message driven bean have and how do they work in collaboration with JMS? - Message driven beans are the latest addition to the family of component bean types defined by the EJB specification. The original bean types include session beans, which contain business logic and maintain a state associated with client sessions, and entity beans, which map objects to persistent data. Message driven beans will provide asynchrony to EJB based applications by acting as JMS message consumers. A message bean is associated with a JMS topic or queue and receives JMS messages sent by EJB clients or other beans. Unlike entity beans and session beans, message beans do not have home or remote interfaces. Instead, message driven beans are instantiated by the container as required. Like stateless session beans, message beans maintain no client-specific state, allowing the container to optimally manage a pool of message-bean instances. Clients send JMS messages to message beans in exactly the same manner as they would send messages to any other JMS destination. This similarity is a fundamental design goal of the JMS capabilities of the new specification. To receive JMS messages, message driven beans implement the javax.jms.MessageListener interface, which defines a single “onMessage()” method. When a message arrives, the container ensures that a message bean corresponding to the message topic/queue exists (instantiating it if necessary), and calls its onMessage method passing the client’s message as the single argument. The message bean’s implementation of this method contains the business logic required to process the message. Note that session beans and entity beans are not allowed to function as message beans. Does RMI-IIOP support code downloading for Java objects sent by value across an IIOP connection in the same way as RMI does across a JRMP connection? - Yes. The JDK 1.2 support the dynamic class loading. The EJB container implements the EJBHome and EJBObject classes. For every request from a unique client, does the container create a separate instance of the generated EJBHome and EJBObject classes? - The EJB container maintains an instance pool. The container uses these instances for the EJB Home reference irrespective of the client request. while refering the EJB Object classes the container creates a separate

Page 66: Java Interview

instance for each client request. The instance pool maintainence is up to the implementation of the container. If the container provides one, it is available otherwise it is not mandatory for the provider to implement it. Having said that, yes most of the container providers implement the pooling functionality to increase the performance of the application server. The way it is implemented is again up to the implementer. What is the advantage of putting an Entity Bean instance from the “Ready State” to “Pooled state”? - The idea of the “Pooled State” is to allow a container to maintain a pool of entity beans that has been created, but has not been yet “synchronized” or assigned to an EJBObject. This mean that the instances do represent entity beans, but they can be used only for serving Home methods (create or findBy), since those methods do not relay on the specific values of the bean. All these instances are, in fact, exactly the same, so, they do not have meaningful state. Jon Thorarinsson has also added: It can be looked at it this way: If no client is using an entity bean of a particular type there is no need for cachig it (the data is persisted in the database). Therefore, in such cases, the container will, after some time, move the entity bean from the “Ready State” to the “Pooled state” to save memory. Then, to save additional memory, the container may begin moving entity beans from the “Pooled State” to the “Does Not Exist State”, because even though the bean’s cache has been cleared, the bean still takes up some memory just being in the “Pooled State”. Can a Session Bean be defined without ejbCreate() method? - The ejbCreate() methods is part of the bean’s lifecycle, so, the compiler will not return an error because there is no ejbCreate() method. However, the J2EE spec is explicit: 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. You need a reference to your EJBObject to startwith. For that Sun insists on putting a method for creating that reference (create method in the home interface). The EJBObject does matter here. Not the actual bean. Is it possible to share an HttpSession between a JSP and EJB? What happens when I change a value in the HttpSession from inside an EJB? - You can pass the HttpSession as parameter to an EJB method, only if all objects in session are serializable.This has to be consider as “passed-by-value”, that means that it’s read-only in the EJB. If anything is altered from inside the EJB, it won’t be reflected back to the HttpSession of the Servlet Container.The “pass-by-reference” can be used between EJBs Remote Interfaces, as they are remote references. While it IS possible to pass an HttpSession as a parameter

Page 67: Java Interview

to an EJB object, it is considered to be “bad practice (1)” in terms of object oriented design. This is because you are creating an unnecessary coupling between back-end objects (ejbs) and front-end objects (HttpSession). Create a higher-level of abstraction for your ejb’s api. Rather than passing the whole, fat, HttpSession (which carries with it a bunch of http semantics), create a class that acts as a value object (or structure) that holds all the data you need to pass back and forth between front-end/back-end. Consider the case where your ejb needs to support a non-http-based client. This higher level of abstraction will be flexible enough to support it. (1) Core J2EE design patterns (2001) Is there any way to read values from an entity bean without locking it for the rest of the transaction (e.g. read-only transactions)? We have a key-value map bean which deadlocks during some concurrent reads. Isolation levels seem to affect the database only, and we need to work within a transaction. - The only thing that comes to (my) mind is that you could write a ‘group accessor’ - a method that returns a single object containing all of your entity bean’s attributes (or all interesting attributes). This method could then be placed in a ‘Requires New’ transaction. This way, the current transaction would be suspended for the duration of the call to the entity bean and the entity bean’s fetch/operate/commit cycle will be in a separate transaction and any locks should be released immediately. Depending on the granularity of what you need to pull out of the map, the group accessor might be overkill. What is the difference between a “Coarse Grained” Entity Bean and a “Fine Grained” Entity Bean? - A ‘fine grained’ entity bean is pretty much directly mapped to one relational table, in third normal form. A ‘coarse grained’ entity bean is larger and more complex, either because its attributes include values or lists from other tables, or because it ‘owns’ one or more sets of dependent objects. Note that the coarse grained bean might be mapped to a single table or flat file, but that single table is going to be pretty ugly, with data copied from other tables, repeated field groups, columns that are dependent on non-key fields, etc. Fine grained entities are generally considered a liability in large systems because they will tend to increase the load on several of the EJB server’s subsystems (there will be more objects exported through the distribution layer, more objects participating in transactions, more skeletons in memory, more EJB Objects in memory, etc.) What is EJBDoclet? - EJBDoclet is an open source JavaDoc doclet that generates a lot of the EJB related source files from custom JavaDoc comments tags embedded in the EJB source file. Is “abc” a primitive value? - The String literal “abc” is not a primitive value. It is a String object.

Page 68: Java Interview

What restrictions are placed on the values of each case of a switch statement? - During compilation, the values of each case of a switch statement must evaluate to a value that can be promoted to an int value. What modifiers may be used with an interface declaration? - An interface may be declared as public or abstract. Is a class a subclass of itself? - A class is a subclass of itself. What is the difference between a while statement and a do statement? - A while statement checks at the beginning of a loop to see whether the next loop iteration should occur. A do statement checks at the end of a loop to see whether the next iteration of a loop should occur. The do statement will always execute the body of a loop at least once. What modifiers can be used with a local inner class? - A local inner class may be final or abstract. What is the purpose of the File class? - The File class is used to create objects that provide access to the files and directories of a local file system. Can an exception be rethrown? - Yes, an exception can be rethrown. When does the compiler supply a default constructor for a class? - The compiler supplies a default constructor for a class if no other constructors are provided. 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. Which non-Unicode letter characters may be used as the first character of an identifier? - The non-Unicode letter characters $ and _ may appear as the first character of an identifier What restrictions are placed on method overloading? - Two methods may not have the same name and argument list but different return types. What is casting? - There are two types of casting, casting between primitive numeric types and casting between object references. Casting between numeric types is used to convert larger values, such as double values, to smaller values, such as byte values. Casting between object references is used to refer to an object by a compatible class, interface, or array type reference. What is the return type of a program’s main() method? - A program’s main() method has a void return type. What class of exceptions are generated by the Java run-time system? - The Java runtime system generates RuntimeException and Error exceptions.

Page 69: Java Interview

What class allows you to read objects directly from a stream? - The ObjectInputStream class supports the reading of objects from input streams. What is the difference between a field variable and a local variable? - A field variable is a variable that is declared as a member of a class. A local variable is a variable that is declared local to a method. How are this() and super() used with constructors? - this() is used to invoke a constructor of the same class. super() is used to invoke a superclass constructor. What is the relationship between a method’s throws clause and the exceptions that can be thrown during the method’s execution? - A method’s throws clause must declare any checked exceptions that are not caught within the body of the method. Why are the methods of the Math class static? - So they can be invoked as if they are a mathematical code library. What are the legal operands of the instanceof operator? - The left operand is an object reference or null value and the right operand is a class, interface, or array type. What an I/O filter? - An I/O filter is an object that reads from one stream and writes to another, usually altering the data in some way as it is passed from one stream to another. If an object is garbage collected, can it become reachable again? - Once an object is garbage collected, it ceases to exist. It can no longer become reachable again. What are E and PI? - E is the base of the natural logarithm and PI is mathematical value pi. Are true and false keywords? - The values true and false are not keywords. What is the difference between the File and RandomAccessFile classes? - The File class encapsulates the files and directories of the local file system. The RandomAccessFile class provides the methods needed to directly access data contained in any part of a file. What happens when you add a double value to a String? - The result is a String object. What is your platform’s default character encoding? - If you are running Java on English Windows platforms, it is probably Cp1252. If you are running Java on English Solaris platforms, it is most likely 8859_1. Which package is always imported by default? - The java.lang package is always imported by default. What interface must an object implement before it can be written to a stream as an object? - An object must implement the Serializable or Externalizable interface before it can be written to a stream as an object.

Page 70: Java Interview

How can my application get to know when a HttpSession is removed? - Define a Class HttpSessionNotifier which implements HttpSessionBindingListener and implement the functionality what you need in valueUnbound() method. Create an instance of that class and put that instance in HttpSession. . Why does it take so much time to access an Applet having Swing Components the first time? - Because behind every swing component are many Java objects and resources. This takes time to create them in memory. JDK 1.3 from Sun has some improvements which may lead to faster execution of Swing applications. Which protocol is used in JNDI Mechansim? t3. What are the differences between == and .equals() ? == compare rerefences and .equals should compare contents. What would return “abc”==”abc” ? true, because of JVM optimisations. What would return new String(”abc”)==new String(”abc”): return false because its 2 differents object. what is a singleton class? The main purpose behind the class is simply to ensure that an application (or a web session, if you’re not a total purist) creates only one instance of a class. This is done in order to do things like control resources (only one factory class is needed per application) or to control business logic access (facades only need to have one instance per application as well). Preventing users from re-instantiating the class and doing unwanted things with it is a happy side effect of the pattern too. What is the query used to display all tables names in SQL Server (Query analyzer)?

select * from information_schema.tablesHow many types of JDBC Drivers are present and what are they?- There are 4 types of JDBC Drivers JDBC-ODBC Bridge Driver Native API Partly Java Driver Network protocol Driver JDBC Net pure Java Driver Can we implement an interface in a JSP?- No What is the difference between ServletContext and PageContext?- ServletContext: Gives the information about the container. PageContext: Gives the information about the Request What is the difference in using request.getRequestDispatcher() and context.getRequestDispatcher()?- request.getRequestDispatcher(path): In order to create it we need to give the relative path of the resource, context.getRequestDispatcher(path): In order to create it we need to give the absolute path of the resource.

Page 71: Java Interview

How to pass information from JSP to included JSP?- Using <%jsp:param> tag. What is the difference between directive include and jsp include?- <%@ include>: Used to include static resources during translation time. JSP include: Used to include dynamic content or static content during runtime. What is the difference between RequestDispatcher and sendRedirect?- RequestDispatcher: server-side redirect with request and response objects. sendRedirect : Client-side redirect with new request and response objects. How does JSP handle runtime exceptions?- Using errorPage attribute of page directive and also we need to specify isErrorPage=true if the current page is intended to URL redirecting of a JSP. How do you delete a Cookie within a JSP?

Cookie mycook = new Cookie(\”name\”,\”value\”);response.addCookie(mycook);Cookie killmycook = new Cookie(\”mycook\”,\”value\”);killmycook.setMaxAge(0);killmycook.setPath(\”/\”);killmycook.addCookie(killmycook);

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

<!--#include file=”data.inc”-->But it’s a little trickier if you want the server to evaluate any JSP code that’s inside the included file. If your data.inc file contains jsp code you will have to use

<%@ vinclude=”data.inc” %>The <!–#include file=”data.inc”–> is used for including non-JSP files.I made my class Cloneable but I still get Can’t access protected method clone. Why?- Some of the Java books imply that all you have to do in order to have your class support clone() is implement the Cloneable interface. Not so. Perhaps that was the intent at some point, but that’s not the way it works currently. As it stands, you have to implement your own public clone() method, even if it doesn’t do anything special and just calls super.clone(). Why is XML such an important development?- It removes two constraints which were holding back Web developments: dependence on a single, inflexible document type (HTML) which was being much abused for tasks it was never designed for; the complexity of full SGML, whose syntax allows many powerful but hard-to-program options. XML allows the flexible development of user-defined document types. It provides a robust, non-proprietary, persistent, and verifiable file format for the storage and transmission of text and data both on and off the Web; and it removes the more complex options of SGML, making it easier to program for.

Page 72: Java Interview

What is the fastest type of JDBC driver?- JDBC driver performance will depend on a number of issues: the quality of the driver code, the size of the driver code, the database server and its load, network topology, the number of times your request is translated to a different API.In general, all things being equal, you can assume that the more your request and response change hands, the slower it will be. This means that Type 1 and Type 3 drivers will be slower than Type 2 drivers (the database calls are make at least three translations versus two), and Type 4 drivers are the fastest (only one translation).How do I find whether a parameter exists in the request object? boolean hasFoo = !(request.getParameter(\”foo\”) == null

|| request.getParameter(\”foo\”).equals(\”\”));orboolean hasParameter =

request.getParameterMap().contains(theParameter); //(which works in Servlet 2.3+)How can I send user authentication information while makingURLConnection?- You’ll want to use HttpURLConnection.setRequestProperty and set all the appropriate headers to HTTP authorization.

Advanced EJB interview questionsAre enterprise beans allowed to use Thread.sleep()? - Enterprise beans make use of the services provided by the EJB container, such as life-cycle management. To avoid conflicts with these services, enterprise beans are restricted from performing certain operations: Managing or synchronizing threads Is it possible to write two EJB’s that share the same Remote and Home interfaces, and have different bean classes? if so, what are the advantages/disadvantages? - It’s certainly possible. In fact, there’s an example that ships with the Inprise Application Server of an Account interface with separate implementations for CheckingAccount and SavingsAccount, one of which was CMP and one of which was BMP. Is it possible to specify multiple JNDI names when deploying an EJB? - No. To achieve this you have to deploy your EJB multiple times each specifying a different JNDI name. Is there any way to force an Entity Bean to store itself to the db? I don’t wanna wait for the container to update the db, I want to do it NOW! Is it possible? - Specify the transaction attribute of the bean as RequiresNew. Then as per section 11.6.2.4 of the EJB v 1.1 spec EJB container automatically starts a new transaction before the method

Page 73: Java Interview

call. The container also performs the commit protocol before the method result is sent to the client. I am developing a BMP Entity bean. I have noticed that whenever the create method is invoked, the ejbLoad() and the ejbStore() methods are also invoked. I feel that once my database insert is done, having to do a select and update SQL queries is major overhead. is this behavior typical of all EJB containers? Is there any way to suppress these invocations? - This is the default behaviour for EJB. The specification states that ejbLoad() will be called before every transaction and ejbStore() after every transaction. Each Vendor has optimizations, which are proprietary for this scenario. Can an EJB send asynchronous notifications to its clients? - Asynchronous notification is a known hole in the first versions of the EJB spec. The recommended solution to this is to use JMS, which is becoming available in J2EE-compliant servers. The other option, of course, is to use client-side threads and polling. This is not an ideal solution, but it’s workable for many scenarios. How can I access EJB from ASP? - You can use the Java 2 Platform, Enterprise Edition Client Access Services (J2EETM CAS) COM Bridge 1.0, currently downloadable from Sun Is there a guarantee of uniqueness for entity beans? - There is no such guarantee. The server (or servers) can instantiate as many instances of the same underlying Entity Bean (with the same PK) as it wants. However, each instance is guaranteed to have up-to-date data values, and be transactionally consistent, so uniqueness is not required. This allows the server to scale the system to support multiple threads, multiple concurrent requests, and multiple hosts. How do the six transaction attributes map to isolation levels like “dirty read”? Will an attribute like “Required” lock out other readers until I’m finished updating? - The Transaction Attributes in EJB do not map to the Transaction Isolation levels used in JDBC. This is a common misconception. Transaction Attributes specify to the container when a Transaction should be started, suspended(paused) and committed between method invocations on Enterprise JavaBeans. For more details and a summary of Transaction Attributes refer to section 11.6 of the EJB 1.1 specification. I have created a remote reference to an EJB in FirstServlet. Can I put the reference in a servlet session and use that in SecondServlet? - Yes. The EJB client (in this case your servlet) acquires a remote reference to an EJB from the Home Interface; that reference is serializable and can be passed from servlet to servlet. If it is a session bean, then the EJB server will consider your web client’s servlet session to correspond to a single EJB session, which is usually (but not always) what you want. Can the primary key in the entity bean be a Java primitive type such as int? - The primary key can’t be a primitive type–use the

Page 74: Java Interview

primitive wrapper classes, instead. For example, you can use java.lang.Integer as the primary key class, but not int (it has to be a class, not a primitive) What’s new in the EJB 2.0 specification? - Following are the main features supported in EJB 2.0: Integration of EJB with JMS, Message Driven Beans, Implement additional Business methods in Home interface which are not specific for bean instance, EJB QL. How many types of protocol implementations does RMI have? - RMI has at least three protocol implementations: Java Remote Method Protocol(JRMP), Internet Inter ORB Protocol(IIOP), and Jini Extensible Remote Invocation(JERI). These are alternatives, not part of the same thing, All three are indeed layer 6 protocols for those who are still speaking OSI reference model. What is the need of Remote and Home interfaces. Why can’t there be one? - In a few words, I would say that the main reason is because there is a clear division of roles and responsabilities between the two interfaces. The home interface is your way to communicate with the container, that is who is responsable of creating, locating even removing one or more beans. The remote interface is your link to the bean, that will allow you to remotely access to all its methods and members. As you can see there are two distinct elements (the container and the beans) and you need two different interfaces for accessing to both of them. What is the difference between Java Beans and EJB? - Java Beans are client-side objects and EJBs are server side object, and they have completely different development, lifecycle, purpose. Question With regard to Entity Beans, what happens if both my EJB Server and Database crash, what will happen to unsaved changes? Is there any transactional log file used? - Actually, if your EJB server crashes, you will not even be able to make a connection to the server to perform a bean lookup, as the server will no longer be listening on the port for incoming JNDI lookup requests. You will lose any data that wasn’t committed prior to the crash. This is where you should start looking into clustering your EJB server. Any unsaved and uncommited changes are lost the moment your EJB Server crashes. If your database also crashes, then all the saved changes are also lost unless you have some backup or some recovery mechanism to retrieve the data. So consider database replication and EJB Clustering for such scenarios, though the occurence of such a thing is very very rare. Thx, Uma All databse have the concept of log files(for exampe oracle have redo log files concept). So if data bases crashes then on starting up they fill look up the log files to perform all pending jobs. But is EJB crashes, It depend upon the container how frequenlty it passivates or how frequesntly it refreshes the data with Database. Question Can you control when passivation occurs? - The developer, according to the specification, cannot directly control when

Page 75: Java Interview

passivation occurs. Although for Stateful Session Beans, the container cannot passivate an instance that is inside a transaction. So using transactions can be a a strategy to control passivation. The ejbPassivate() method is called during passivation, so the developer has control over what to do during this exercise and can implement the require optimized logic. Some EJB containers, such as BEA WebLogic, provide the ability to tune the container to minimize passivation calls. Taken from the WebLogic 6.0 DTD - “The passivation-strategy can be either “default” or “transaction”. With the default setting the container will attempt to keep a working set of beans in the cache. With the “transaction” setting, the container will passivate the bean after every transaction (or method call for a non-transactional invocation).” Does RMI-IIOP support dynamic downloading of classes? - No, RMI-IIOP doesn’t support dynamic downloading of the classes as it is done with CORBA in DII (Dynamic Interface Invocation).Actually RMI-IIOP combines the usability of Java Remote Method Invocation (RMI) with the interoperability of the Internet Inter-ORB Protocol (IIOP).So in order to attain this interoperability between RMI and CORBA,some of the features that are supported by RMI but not CORBA and vice versa are eliminated from the RMI-IIOP specification. Does EJB 1.1 support mandate the support for RMI-IIOP ? What is the meaning of “the client API must support the Java RMI-IIOP programming model for portability, but the underlying protocol can be anything” ? - EJB1.1 does mandate the support of RMI-IIOP. There are 2 types of implementations that an EJB Server might provide: CORBA-based EJB Servers and Proprietry EJB Servers. Both support the RMI-IIOP API but how that API is implemented is a different story. (NB: By API we mean the interface provided to the client by the stub or proxy). A CORBA-based EJB Server actually implements its EJB Objects as CORBA Objects (it therefore encorporates an ORB and this means that EJB’s can be contacted by CORBA clients (as well as RMI-IIOP clients) A proprietry EJB still implements the RMI-IIOP API (in the client’s stub) but the underlying protocol can be anything. Therefore your EJB’s CANNOT be contacted by CORBA clients. The difference is that in both cases, your clients see the same API (hence, your client portability) BUT how the stubs communicate with the server is different. The EJB specification says that we cannot use Bean Managed Transaction in Entity Beans. Why? - The short, practical answer is… because it makes your entity beans useless as a reusable component. Also, transaction management is best left to the application server - that’s what they’re there for. It’s all about atomic operations on your data. If an operation updates more than one entity then you want the whole thing to succeed or the whole thing to fail, nothing in between. If you put commits in the entity beans then it’s very difficult to rollback if an error occurs at some point late in the operation.

Page 76: Java Interview

Can I invoke Runtime.gc() in an EJB? - You shouldn’t. What will happen depends on the implementation, but the call will most likely be ignored. You should leave system level management like garbage collection for the container to deal with. After all, that’s part of the benefit of using EJBs, you don’t have to manage resources yourself. What is clustering? What are the different algorithms used for clustering? - Clustering is grouping machines together to transparantly provide enterprise services.The client does not now the difference between approaching one server or approaching a cluster of servers.Clusters provide two benefits: scalability and high availability. Further information can be found in the JavaWorld article J2EE Clustering. What is the advantage of using Entity bean for database operations, over directly using JDBC API to do database operations? When would I use one over the other? - Entity Beans actually represents the data in a database. It is not that Entity Beans replaces JDBC API. There are two types of Entity Beans Container Managed and Bean Mananged. In Container Managed Entity Bean - Whenever the instance of the bean is created the container automatically retrieves the data from the DB/Persistance storage and assigns to the object variables in bean for user to manipulate or use them. For this the developer needs to map the fields in the database to the variables in deployment descriptor files (which varies for each vendor). In the Bean Managed Entity Bean - The developer has to specifically make connection, retrive values, assign them to the objects in the ejbLoad() which will be called by the container when it instatiates a bean object. Similarly in the ejbStore() the container saves the object values back the the persistance storage. ejbLoad and ejbStore are callback methods and can be only invoked by the container. Apart from this, when you use Entity beans you dont need to worry about database transaction handling, database connection pooling etc. which are taken care by the ejb container. But in case of JDBC you have to explicitly do the above features. what suresh told is exactly perfect. ofcourse, this comes under the database transations, but i want to add this. the great thing about the entity beans of container managed, whenever the connection is failed during the transaction processing, the database consistancy is mantained automatically. the container writes the data stored at persistant storage of the entity beans to the database again to provide the database consistancy. where as in jdbc api, we, developers has to do manually. What is the role of serialization in EJB? - A big part of EJB is that it is a framework for underlying RMI: remote method invocation. You’re invoking methods remotely from JVM space ‘A’ on objects which are in JVM space ‘B’ — possibly running on another machine on the network. To make this happen, all arguments of each method call must have their current state plucked out of JVM ‘A’ memory, flattened into a byte

Page 77: Java Interview

stream which can be sent over a TCP/IP network connection, and then deserialized for reincarnation on the other end in JVM ‘B’ where the actual method call takes place. If the method has a return value, it is serialized up for streaming back to JVM A. Thus the requirement that all EJB methods arguments and return values must be serializable. The easiest way to do this is to make sure all your classes implement java.io.Serializable. What is EJB QL? - EJB QL is a Query Language provided for navigation across a network of enterprise beans and dependent objects defined by means of container managed persistence. EJB QL is introduced in the EJB 2.0 specification. The EJB QL query language defines finder methods for entity beans with container managed persistenceand is portable across containers and persistence managers. EJB QL is used for queries of two types of finder methods: Finder methods that are defined in the home interface of an entity bean and which return entity objects. Select methods, which are not exposed to the client, but which are used by the Bean Provider to select persistent values that are maintained by the Persistence Manager or to select entity objects that are related to the entity bean on which the query is defined.

Serialization:

Serialization is the process of converting a set of object instances that contain references to each other into a linear stream of bytes, which can then be sent through a socket, stored to a file, or simply manipulated as a stream of data. Serialization is the mechanism used by RMI to pass objects between JVMs, either as arguments in a method invocation from a client to a server or as return values from a method invocation. In the first section of this book, I referred to this process several times but delayed a detailed discussion until now. In this chapter, we drill down on the serialization mechanism; by the end of it, you will understand exactly how serialization works and how to use it efficiently within your applications.

The Need for Serialization

Envision the banking application while a client is executing a withdrawal. The part of the

application we're looking at has the runtime structure shown in Figure 10-1.

Page 78: Java Interview

What does it mean for the client to pass an instance of Moneyto the server? At a minimum, it

means that the server is able to call public methods on the instance of Money.

One way to do this would be to implicitly make Moneyinto a server as well. For example, imagine that the client sends the following two pieces of information whenever it passes an instance as an argument:

The type of the instance; in this case, Money. A unique identifier for the object (i.e., a logical reference). For example, the address of

the instance in memory.

The RMI runtime layer in the server can use this information to construct a stub for the instance of Money, so that whenever the Accountserver calls a method on what it thinks of as

the instance of Money, the method call is relayed over the wire, as shown in Figure 10-2.

Figure 10-2. Relaying a Money method call from the server

Attempting to do things this way has three significant drawbacks:

You can't access fields on the objects that have been passed as arguments. It can result in unacceptable performance due to network latency.

Even in our simple case, the instance of Accountis going to need to call

getCents( )on the instance of Money. This means that a simple call to

makeDeposit( )really involves at least two distinct networked method calls:

makeDeposit( )from the client and getCents( )from the server.

It makes the application much more vulnerable to partial failure.

Let's say that the server is busy and doesn't get around to handling the request for 30 seconds. If the client crashes in the interim, or if the network goes down, the server cannot process the request at all. Until all data has been requested and sent, the application is particularly vulnerable to partial failures.

These three reasons imply that what is really needed is a way to copy objects and send them over the wire. That is, instead of turning arguments into implicit servers, arguments need to be completely copied so that no further network calls are needed to complete the remote method invocation. Put another way, we want the result of makeWithdrawal( )to involve creating a

copy of the instance of Moneyon the server side. The runtime structure should resemble Figure 10-3.

Page 79: Java Interview

Figure 10-3. Making a remote method call can create deep copies of the arguments and return values

An object is serializable only if its class implements the Serializable

interface.

Implementing the Externalizable Interface

For complete, explicit control of the serialization process, a class must implement the Externalizable interface. For Externalizable objects, only the identity of the object's class is automatically saved by the stream. The class is responsible for writing and reading its contents, and it must coordinate with its superclasses to do so.

Here's the complete definition of the Externalizable interface that extends Serializable:

package java.io;public interface Externalizable extends Serializable { public void writeExternal(ObjectOutput out) throws IOException; public void readExternal(ObjectInput in) throws IOException, java.lang.ClassNotFoundException;}The following holds for an Externalizable class:

It must implement the java.io.Externalizable interface. It must implement a writeExternal method to save the state of the object. Also, it

must explicitly coordinate with its supertype to save its state. It must implement a readExternal method to read the data written by the

writeExternal method from the stream and restore the state of the object. It must explicitly coordinate with the supertype to restore its state.

If externally defined format is being written, the writeExternal and readExternal methods are solely responsible for that format.

The Externalizable Interface

To solve the performance problems associated with making a class Serializable, the serialization mechanism allows you to declare that a class is Externalizableinstead. When

Page 80: Java Interview

ObjectOutputStream's writeObject( )method is called, it performs the following sequence of actions:

1. It tests to see if the object is an instance of Externalizable. If so, it uses externalization to marshall the object.

2. If the object isn't an instance of Externalizable, it tests to see whether the object is an instance of Serializable. If so, it uses serialization to marshall the object.

3. If neither of these two cases apply, an exception is thrown.

Externalizableis an interface that consists of two methods:

public void readExternal(ObjectInput in);public void writeExternal(ObjectOutput out);

These have roughly the same role that readObject( )and writeObject( )have for serialization. There are, however, some very important differences. The first, and most obvious, is that readExternal( )and writeExternal( )are part of the Externalizableinterface. An object cannot be declared to be Externalizablewithout implementing these methods.

However, the major difference lies in how these methods are used. The serialization mechanism always writes out class descriptions of all the serializable superclasses. And it always writes out the information associated with the instance when viewed as an instance of each individual superclasses.

Externalization gets rid of some of this. It writes out the identity of the class (which boils down to the name of the class and the appropriate serialVersionUID). It also stores the superclass structure and all the information about the class hierarchy. But instead of visiting each superclass and using that superclass to store some of the state information, it simply calls writeExternal( )on the local class definition. In a nutshell: it stores all the metadata, but writes out only the local instance information.

TIP:   This is true even if the superclass implements Serializable. The metadata about the class structure will be written to the stream, but the serialization mechanism will not be invoked. This can be useful if, for some reason, you want to avoid using serialization with the superclass. For example, some of the Swing classes, while they claim to implement Serializable, do so incorrectly (and will throw exceptions during the serialization process). (JTextAreais one of the most egregious offenders.) If you really need to use these classes, and you think serialization would be useful, you may want to think about creating a subclass and declaring it to be Externalizable. Instances of your class will be written out and read in using externalization. Because the superclass is never serialized or deserialized, the incorrect code is never invoked, and the exceptions are never thrown.

Can there be an abstract class with no abstract methods in it? - Yes Can an Interface be final? - No Can an Interface have an inner class? - Yes.

public interface abc{

static int i=0; void dd();

Page 81: Java Interview

class a1{

a1(){

int j;System.out.println(\”inside\”);

};public static void main(String a1[]){

System.out.println(\”in interfia\”);}

}}

Collections A collection — sometimes called a container — is simply an object that groups multiple elements into a single unit. Collections are used to store, retrieve, manipulate, and communicate aggregate data. They typically represent data items that form a natural group, such as a poker hand (a collection of cards), a mail folder (a collection of letters), or a telephone directory (a mapping from names to phone numbers). If you’ve used the Java programming language — or just about any other programming language — you’re already familiar with collections. Collection implementations in earlier (pre-1.2) versions of the Java platform included Vector, Hashtable, and array. Those earlier versions, however, did not contain a collections framework. What Is a Collections Framework?A collections framework is a unified architecture for representing and manipulating collections. All collections frameworks contain: Interfaces: abstract data types representing collections. Interfaces allow collections to be manipulated independently of the details of their representation. In object-oriented languages, these interfaces generally form a hierarchy. Implementations: concrete implementations of the collection interfaces. In essence, these are reusable data structures. Algorithms: methods that perform useful computations, such as searching and sorting, on objects that implement collection interfaces. These algorithms are said to be polymorphic: the same method can be used on many different implementations of the appropriate collection interface. In essence, algorithms are reusable functionality. Apart from the Java Collections Framework, the best-known examples of collections frameworks are the C++ Standard Template Library (STL) and Smalltalk’s collection hierarchy. Historically, collections frameworks have been quite complex, which gave them a reputation for having a steep learning curve. We believe that the Java Collections

Page 82: Java Interview

Framework breaks with this tradition, as you will learn for yourself in this chapter. Benefits of the Java Collections FrameworkThe Java Collections Framework provides the following benefits: Reduces programming effort: By providing useful data structures and algorithms, the Collections Framework frees you to concentrate on the important parts of your program rather than on the low-level plumbing required to make it work. By facilitating interoperability among unrelated APIs, the Collections Framework frees you from writing adapter objects or conversion code to connect APIs. Increases program speed and quality: The Collections Framework provides high-performance, high-quality implementations of useful data structures and algorithms. The various implementations of each interface are interchangeable, so programs can be easily tuned by switching collection implementations. Because youre freed from the drudgery of writing your own data structures, youll have more time to devote to improving your programs quality and performance. Allows interoperability among unrelated APIs: The collection interfaces are the vernacular by which APIs pass collections back and forth. If my network administration API furnishes a Collection of node names and if your GUI toolkit expects a Collection of column headings, our APIs will interoperate seamlessly, even though they were written independently. Reduces effort to learn and to use new APIs: Many APIs naturally take collections on input and furnish them as output. In the past, each such API had a little sub-API devoted to manipulating its collections. There was little consistency among these ad hoc collections sub-APIs, so you had to learn each one from scratch, and it was easy to make mistakes when using them. With the advent of standard collection interfaces, the problem went away. Reduces effort to design new APIs: This is the flip side of the previous advantage. Designers and implementers dont have to reinvent the wheel each time they create an API that relies on collections but instead use the standard collection interfaces. Fosters software reuse: New data structures that conform to the standard collection interfaces are by nature reusable. The same goes for new algorithms that operate on objects that implement these interfaces. Interfaces The core collection interfaces encapsulate different types of collections and are shown in the figure below. These interfaces allow collections to be manipulated independently of the details of their representation. The core collection interfaces are the foundation of the Java Collections Framework.

Page 83: Java Interview

As you can see from the figure, the core collection interfaces form a hierarchy: a Set is a special kind of Collection, a SortedSet is a special kind of Set, and so forth. Note also that the hierarchy consists of two distinct trees: a Map is not a true Collection. Note that all of the core collection interfaces are generic. For example, the declaration of the Collection interface is: public interface Collection<E> ...The <E> syntax tells you that the interface is generic. When you declare a <code> Collection instance you can and should specify the type of object contained in the collection. Specifying the type allows the compiler to verify (at compile time) that the type of object you put into the collection is correct, thus reducing errors at runtime. For information on generic types, see the section Generics . When you understand how to use these interfaces, you know most of what there is to know about the Collections Framework. This chapter will discuss general guidelines for effective use of these interfaces, including when to use which interface. You’ll also learn programming idioms for each interface to help you get the most out of it. To keep the number of core collection interfaces manageable, the Java platform doesn’t provide separate interfaces for each variant of each collection type. (Such variants might include immutable, fixed-size, and append-only.) Instead, the modification operations in each interface are designated optional: a given implementation may elect not to support all operations. If an unsupported operation is invoked, a collection throws an UnsupportedOperationException . Implementations are responsible for documenting which of the optional operations they support. All of the Java platform’s general-purpose implementations support all the optional operations. The core collection interfaces are: Collection: The root of the collection hierarchy. A collection represents a group of objects, known as its elements. The Collection interface is the least common denominator that all collections implement, and is used to pass collections around and to manipulate them when maximum generality is desired. Some types of collections allow duplicate elements, and others do not. Some are ordered and others unordered. The Java platform doesn’t provide any direct implementations of this interface but provides implementations of more specific subinterfaces, such as Set and List. See the section The Collection Interface .

Page 84: Java Interview

Set: A collection that cannot contain duplicate elements. This interface models the mathematical set abstraction and is used to represent sets, such as the cards comprising a poker hand, the courses making up a student’s schedule, or the processes running on a machine. See the section The Set Interface . List: An ordered collection (sometimes called a sequence). Lists can contain duplicate elements. The user of a List generally has precise control over where in the List each element is inserted, and can access elements by their integer index (position). If you’ve used Vector, you’re familiar with the general flavor of List. See the section The List Interface

. Queue: A collection used to hold multiple elements prior to processing. Besides basic Collection operations, queues provide additional insertion, extraction, and inspection operations. Queues typically, but do not necessarily, order elements in a FIFO (first-in-first-out) manner. Among the exceptions are priority queues, which order elements according to a supplied comparator, or the elements’ natural ordering. Whatever the ordering used, the head of the queue is that element that would be removed by a call to remove or poll. In a FIFO queue, all new elements are inserted at the tail of the queue. Other kinds of queues may use different placement rules. Every Queue implementation must specify its ordering properties. See the section The Queue Interface . Map: An object that maps keys to values. Maps cannot contain duplicate keys: Each key can map to at most one value. If you’ve used Hashtable, you’re already familiar with the general flavor of Map. See the section The Map Interface . The last two core collection interfaces are merely sorted versions of Set and Map: SortedSet: A Set that maintains its elements in ascending order. Several additional operations are provided to take advantage of the ordering. Sorted sets are used for naturally ordered sets, such as word lists and membership rolls. See the section The SortedSet Interface . SortedMap: A Map that maintains its mappings in ascending key order. This is the Map analog of SortedSet. Sorted maps are used for naturally ordered collections of key/value pairs, such as dictionaries and telephone directories. See the section The SortedMap Interface . To understand how the sorted interfaces maintain the order of their elements, see Object Ordering .

The Collection Interface

A Collection represents a group of objects, known as its elements. The Collection interface is used to pass around collections of objects where maximum generality is desired. For example, by convention all general-purpose collection implementations have a constructor that

Page 85: Java Interview

takes a Collection argument. This constructor, known as a conversion constructor, initializes the new collection to contain all the elements in the specified Collection, whatever the given collection’s subinterface or implementation type. In other words, it allows you to convert the type of the collection. Suppose, for example, that you have a Collection<String> c, which may be a List, a Set, or another kind of Collection. The following idiom creates a new ArrayList (an implementation of the List interface), initially containing all the elements in c: List<String> list = new ArrayList<String>©;The Collection interface is shown below: public interface Collection<E> extends Iterable<E> {// Basic Operationsint size();boolean isEmpty();boolean contains(Object element);boolean add(E element); // Optionalboolean remove(Object element); // OptionalIterator iterator();

// Bulk Operationsboolean containsAll(Collection<?> c);boolean addAll(Collection<? extends E> c); // Optional boolean removeAll(Collection<?> c); // Optional boolean retainAll(Collection<?> c); // Optionalvoid clear(); // Optional// Array OperationsObject[] toArray();<T> T[] toArray(T[] a);}The interface does about what you’d expect, given that a Collection represents a group of objects. The interface has methods to tell you how many elements are in the collection (size, isEmpty), to check whether a given object is in the collection (contains), to add and remove an element from the collection (add, remove), and to provide an iterator over the collection (iterator). The add method is defined generally enough so that it makes sense for collections that allow duplicates as well as those that don’t. It guarantees that the Collection will contain the specified element after the call completes, and returns true if the Collection changes as a result of the call. Similarly, the remove method is defined to remove a single instance of the specified element from the Collection, assuming that it contains the element to start with, and to return true if the Collection was modified as a result.

Traversing Collections

Page 86: Java Interview

There are two ways to traverse collections: with the for-each construct and using iterators. For-Each ConstructThe for-each construct allows you to concisely traverse a collection or array using a for loop The for Statement . The following code uses the for-each construct to print out each element of a collection on a separate line: for (Object o : collection) System.out.println(o);IteratorsAn Iterator is an object that enables you to traverse through a collection, and to remove elements from the collection selectively, if desired. You get an Iterator for a collection by calling its iterator method. The Iterator interface is: public interface Iterator<E> {boolean hasNext();E next();void remove(); // Optional}The hasNext method returns true if the iteration has more elements, and the next method returns the next element in the iteration. The remove method removes from the underlying Collection the last element that was returned by next. The remove method may be called only once per call to next and throws an exception if this rule is violated. Note that Iterator.remove is the only safe way to modify a collection during iteration; the behavior is unspecified if the underlying collection is modified in any other way while the iteration is in progress. Use an iterator instead of the for-each construct when: You need to remove the current element. The for-each construct hides the iterator, so you cannot call remove. Therefore, the for-each construct is not usable for filtering. You need to replace elements in a list or array as you traverse it. You need to iterate over multiple collections in parallel. The following method shows you how to use an iterator to filter an arbitrary Collection (that is, traverse the collection removing specific elements): static void filter(Collection c) {for (Iterator i = c.iterator(); i.hasNext(); ) if (!cond(i.next())) i.remove();}This simple piece of code is polymorphic, which means that it works for any Collection, regardless of implementation. This example demonstrates how easy it is to write a polymorphic algorithm using the Collections Framework.

Page 87: Java Interview

Collection Interface Bulk Operations

The bulk operations perform an operation on an entire Collection. You could implement these shorthand operations using the basic operations, though in most cases such implementations would be less efficient. The bulk operations are: containsAll: Returns true if the target Collection contains all of the elements in the specified Collection. addAll: Adds all the elements in the specified Collection to the target Collection. removeAll: Removes from the target Collection all its elements that are also contained in the specified Collection. retainAll: Removes from the target Collection all its elements that are not also contained in the specified Collection. That is, it retains in the target Collection only those elements that are also contained in the specified Collection. clear: Removes all elements from the Collection. The addAll, removeAll, and retainAll methods all return true if the target Collection was modified in the process of executing the operation. As a simple example of the power of the bulk operations, consider following idiom to remove all instances of a specified element, e from a Collection, c.: c.removeAll(Collections.singleton(e));More specifically, suppose that you want to remove all the null elements from a Collection: c.removeAll(Collections.singleton(null));This idiom uses Collections.singleton, which is a static factory method that returns an immutable Set containing only the specified element.

Collection Interface Array Operations

The toArray methods are provided as a bridge between collections and older APIs that expect arrays on input. The array operations allow the contents of a Collection to be translated into an array. The simple form with no arguments creates a new array of Object. The more complex form allows the caller to provide an array or to choose the runtime type of the output array. For example, suppose that c is a Collection. The following snippet dumps the contents of c into a newly allocated array of Object whose length is identical to the number of elements in c: Object[] a = c.toArray();Suppose that c is known to contain only strings (perhaps because c is of type Collection<String>). The following snippet dumps the contents of c into a newly allocated array of String whose length is identical to the number of elements in c: String[] a = c.toArray(new String[0]);

Page 88: Java Interview

Web application scope

Web components share information with other web components using objects that are maintained as attributes of four types of scope object – web context, session,

request, and page. These attributes can be accessed using the getAttribute or

setAttribute methods of the class that represents the scope.

The web context scope object is an object of the ServletContext class. Its scope is

that of the entire web application so it is available to all servlets and JSPs in the web application. A resource stored in the shared ServletContext is accessible from a JSP

in the predefined application variable, or by invoking getServletContext in a servlet.

The session scope object is an object of the HttpSession class, so its scope is that of

the session and it is accessible to all web components handling a request belonging to the session. The request scope object is a subtype of ServletRequest. Its scope is

that of a single request so it is accessible to all web components handling the request. The most limited scope is page, which is an object of the PageContext class. This is a

JSP class that provides a single point of access for many of the attributes of a JSP page in the predefined pageContext variable.

Sharing web application resources

Shared resources can be accessed concurrently in a multithreaded server. These resources include in-memory data – instance or class variables, for example – and external objects – such as files and database connections – as well as scope object attributes. Concurrent access occurs in a number of situations – for example, when multiple web components want to access objects stored in the web context, or in a session object.

Concurrent access also takes place when multiple threads within a web component need to access instance variables. When the servlet is first created, its init method is

invoked. Each subsequent user request results in a thread that calls the service

method of the previously created instance.

Multiple concurrent requests usually result in multiple threads calling the service

method simultaneously. It then invokes doGet, doPost, or some other doXXX method,

depending on the type of HTTP request received. Because multiple threads may access instance data simultaneously, these methods need to be careful to protect access to shared data and resources – otherwise data and resources shared by servlets could be lost or corrupted.

Implementing thread safety in servlets

You can treat servlet thread handling in either of two ways. You can ensure that each request works independently and doesn't access the servlet instance concurrently, or,

Page 89: Java Interview

you can allow concurrent access while protecting the shared data in the same way as you do in other multithreaded Java applications – that is, by synchronizing access to the data in your service methods.

SingleThreadModel

To prevent multithreaded access and ensure that access to shared data is thread-safe, your servlet class can implement the SingleThreadModel interface. This guarantees

that only a single thread is ever permitted to access the servlet instance at any one time.

public class myServlet extends HttpServlet implements SingleThreadModel

In most cases, the SingleThreadModel interface approach works by queueing the

requests and passing them to a single servlet instance one at a time. However, the server can also create a pool of multiple instances, each of which handles a single request at a time.

For JSPs, you can use the isThreadSafe attribute to control whether a servlet resulting

from a JSP implements the SingleThreadModel interface. This attribute can take two

forms:

<%@ page isThreadSafe="true" %> <%@ page isThreadSafe="false" %>

The default value of the isThreadSafe attribute is "true". This means that the system

assumes that the servlet is threadsafe, and consequently allows multithreaded access to a single servlet instance.

To indicate that your code is not threadsafe, you need to set the isThreadSafe to

"false". The servlet resulting from the JSP will then implement the SingleThreadModel interface. (This behavior is useful for quick testing, and when problematic code is hard to find.)

When you implement the SingleThreadModel interface, you still have to synchronize

access to class variables and to any shared resources that are stored outside the servlet. Also, you need to take into account that if your servlet is accessed frequently, when it is waiting for I/O the server remains idle instead of handling pending requests, and this can significantly affect performance.

Synchronizing access

To guarantee threadsafe access to shared resources in a multithreaded servlet, you need to use synchronized blocks of code. This ensures that, once a thread enters a block of code, no other thread can enter the same block – or any other block with the same object reference – until the first thread has executed.

Page 90: Java Interview

public void doPost(HttpServletRequest req,             HttpServletResponse res)            throws ServletException, IOException {

    //More code here

    synchronized(myResource) {        if(req.getParameter("ADD") != null)            myResource.total = myResource.total + 1;        if(req.getParameter("SUBTRACT") != null)            myResource.total = myResource.total - 1;    }}

Choosing an approach

For high-traffic servlets, you should use explicit synchronized blocks rather than implementing the SingleThreadModel interface. Explicitly synchronizing your code is

preferable whenever possible because it yields higher performance for pages that are accessed frequently. However, either method of handling servlet threading can be used to prevent simultaneous access to the servlet's instance variables and shared resources.

Synchronization is not an issue when writing servlets that perform a task but don't return data from another source. Servlets such as these can usually store their data in local variables and thereby prevent conflict between threads executing the service method.

Also, in certain cases, you will work with shared resources to which you require no more than read-only access. Because resource access conflicts arise only when resources are being written to, multithreading should not cause any problems in this situation.

Summary

Collaborating web components can share information using objects maintained as attributes of four types of scope object – ServletContext, HttpSession,

ServletRequest, and PageContext. You can access these attributes using the

getAttribute or setAttribute methods of the class representing the scope.

In a multithreaded server, shared data and resources can be accessed concurrently in a number of situations – for example, when multiple web components access a shared resource in a scope object, or when multiple threads within a web component access instance variables. Multiple concurrent requests generally result in multiple threads invoking the service method simultaneously, and this introduces a risk of shared data or resources being lost or corrupted.

Page 91: Java Interview

You can treat servlet thread handling in two ways. You can either implement the SingleThreadModel – which guarantees that only a single request accesses a servlet

instance at a time – or, you can protect shared data and resources by using synchronized blocks of code within your service methods. In general, it is better to explicitly synchronize your code as this yields higher performance. However, synchronization is not necessary if you require read-only access to shared resources, or if the servlet doesn't need to return data from another source.

Threads And Synchronization

current thread The thread that associates with the Thread (or Thread subclass) object whose reference Thread.currentThread() returns. daemon thread A thread that performs housekeeping (such as garbage collection) and other background tasks that probably do not contribute to the application's main work but are necessary for the application to continue its main work. multithreading The act of multiple threads executing byte code instruction sequences in the same program. runnable An object created from a class that implements the Runnable interface. thread An independent path of execution through program code. user thread A thread that performs important work for the program's user that must finish before the application terminatesTIPS1.If you need access to a Thread object that describes the current thread, call Thread's static currentThread() method. Example: Thread current = Thread.currentThread ();.2.When you face a situation where a class can either extend Thread or implement Runnable, which approach do you choose? If the class already extends another class, you must implement Runnable. However, if that class extends no other class, think about the class name. That name will suggest that the class's objects are either active or passive. For example, the name Ticker suggests that its objects are active—they tick. Thus, the Ticker class would extend Thread, and Ticker objects would be specialized Thread objects. In contrast, Rectangle suggests passive objects—Rectangle objects do nothing on their own. Thus, the Rectangle class would implement Runnable, and Rectangle objects would use Thread objects (for testing or other purposes) instead of being specialized Thread objects.

Sun Microsystems has deprecated a variety of Thread methods, such as suspend() and resume(), because they can lock up your programs or damage objects. As a result, you should not call

Page 92: Java Interview

them in your code. Consult the SDK documentation for workarounds to those methods.

After a thread calls start(), subsequent calls to that method before the run() method exits cause start() to throw a java.lang.IllegalThreadStateException object.

Do not attempt to join the current thread to itself because the current thread will wait forever.

The setDaemon(boolean isDaemon) method throws an IllegalThreadStateException object if a call is made to that method after the thread starts execution.

3. in many interesting situations, separate, concurrently running threads do share data and must consider the state and activities of other threads. In one such set of programming situations, called producer-consumer scenarios, the producer generates a stream of data that a consumer uses.

For example, imagine an application in which one thread (the producer) writes data to a file while a second thread (the consumer) reads data from the same file. Or, as you type characters on the keyboard, the producer thread places mouse events in an event queue and the consumer thread reads the events from the same queue. Both use concurrent threads that share a common resource: the first shares a file; the second shares an event queue. Because the threads share a common resource, they must be synchronized.

The Producer/Consumer Example In this example, the Producer generates an integer between 0 and 9 (inclusive), then stores it in a CubbyHole object. To make the synchronization problem more interesting, the Producer sleeps for a random amount of time between 0 and 100 milliseconds before repeating the number-generating cycle. public class Producer extends Thread { private CubbyHole cubbyhole; private int number;

public Producer(CubbyHole c, int number) { cubbyhole = c; this.number = number; }

public void run() { for (int i = 0; i < 10; i++) { cubbyhole.put(number, i); try { sleep((int)(Math.random() * 100)); } catch (InterruptedException e) { } } }}The Consumer consumes all integers from the CubbyHole (the exact same object into which the Producer put the integers in the first place) as quickly as they become available.

Page 93: Java Interview

public class Consumer extends Thread { private CubbyHole cubbyhole; private int number;

public Consumer(CubbyHole c, int number) { cubbyhole = c; this.number = number; }

public void run() { int value = 0; for (int i = 0; i < 10; i++) { value = cubbyhole.get(number); } }}The Producer and Consumer examples share data through a common CubbyHole object. Although, ideally, Consumer will get each value produced once and only once, neither Producer nor Consumer makes any effort whatsoever to ensure that this happens. The synchronization between these two threads occurs at a lower level within the get and put methods of the CubbyHole object. Assume for a moment, however, that the two threads make no arrangements for synchronization; let's discuss the potential problems that might arise from this. One problem arises when the Producer is quicker than the Consumer and generates two numbers before the Consumer has a chance to consume the first one. In this situation, the Consumer misses a number. Part of the output might look like the following figure.

Consumer misses number.

Another problem might arise when the Consumer is quicker than the Producer and consumes the same value twice. In this situation, the Consumer might produce the output shown in the following figure.

Consumer gets the same number twice.

Either way, the result is wrong because the Consumer should get each integer produced by the Producer exactly once. A problem like this is called a race condition. A race

Page 94: Java Interview

condition is a situation in which two or more threads or processes are reading or writing some shared data, and the final result depends on the timing of how the threads are scheduled. Race conditions can lead to unpredictable results and subtle program bugs. Race conditions in the producer-consumer example are prevented by having storage of a new integer in the CubbyHole by the Producer synchronized with retrieval of an integer from the CubbyHole by the Consumer. The activities of the Producer and the Consumer must be synchronized in two ways. First, the two threads must not simultaneously access the CubbyHole. A thread can prevent this from happening by locking an object. When an object is locked by one thread and another thread tries to call a synchronized method on the same object, the second thread will be blocked until the object is unlocked. Second, the two threads must do some simple coordination. That is, the Producer must have a way to indicate to the Consumer that the value is ready, and the Consumer must have a way to indicate that the value has been retrieved. The Object class provides a collection of methods — wait, notify, and notifyAll — to help threads wait for a condition and to notify other threads when that condition changes.

Locking an Object Within a program, the code segments that access the same object from separate, concurrent threads are called critical sections. A critical section can be a block or a method and is identified with the synchronized keyword. The Java platform associates a lock with every object and the lock is acquired when a critical section is entered. In the producer-consumer example, the put and get methods of CubbyHole.java are the critical sections. The Consumer should not access the CubbyHole when the Producer is changing it, and the Producer should not modify it when the Consumer is getting the value. So, put and get in the CubbyHole class should be marked with the synchronized keyword. The following is a code skeleton for the CubbyHole class. public class CubbyHole { private int contents; private boolean available = false;

public synchronized int get(int who) { ... }

public synchronized void put(int who, int value) { ... }}The method declarations for both put and get contain the synchronized keyword. Whenever control enters a synchronized method, the thread that called the method locks the object whose method has been called. Other threads cannot call a synchronized method on the same object until the object is unlocked.

Thus, when it calls CubbyHole's put method, the Producer locks the CubbyHole, thereby preventing the Consumer from calling CubbyHole's get method.

Page 95: Java Interview

public synchronized void put(int value) { //CubbyHole locked by the Producer. ... //CubbyHole unlocked by the Producer.}When the put method returns, the Producer unlocks the CubbyHole.

Similarly, when the Consumer calls CubbyHole's get method, it locks the CubbyHole, thereby preventing the Producer from calling put.

public synchronized int get() { //CubbyHole locked by the Consumer. ... //CubbyHole unlocked by the Consumer.}The acquisition and release of a lock is done automatically by the Java runtime system. This ensures that race conditions cannot occur in the underlying implementation of the threads, thus ensuring data integrity.

Reacquiring a Lock

The same thread can call a synchronized method on an object for which it already holds the lock, thereby reacquiring the lock. The Java runtime environment allows a thread to reacquire a lock because the locks are reentrant. Reentrant locks are important because they eliminate the possibility of a single thread having to wait for a lock that it already holds.

Consider the following.

public class Reentrant { public synchronized void a() { b(); System.out.format("Here I am, in a().%n"); } public synchronized void b() { System.out.format("Here I am, in b().%n"); }}Reentrant contains two synchronized methods: a and b. The first, a, calls the other, b. When control enters method a, the current thread acquires the lock for the Reentrant object. Now, a calls b; because b is also synchronized, the thread attempts to acquire the same lock again. Because the Java platform supports reentrant locks, this works. In platforms that don't support reentrant locks, this sequence of method calls causes a deadlock. The current thread can acquire the Reentrant object's lock again, and both a and b execute to conclusion, as is evidenced by the following output. Here I am, in b().Here I am, in a().

Page 96: Java Interview

Using the notifyAll and wait Methods

Let's investigate how the code in CubbyHole's put and get methods helps the Producer and the Consumer coordinate their activities. The CubbyHole stores its value in a private member variable called contents. CubbyHole has another private member variable, available, a boolean. The available variable is true when the value has been put but not yet gotten and is false when the value has been gotten but not yet put. Here's one possible implementation for the put and get methods. public synchronized int get() { //Won't work!

if (available == true) {available = false;return contents;

}}

public synchronized void put(int value) { //Won't work!if (available == false) {

available = true;contents = value;

}}As implemented, these two methods won't work. Look at the get method. What happens if the Producer hasn't put anything in the CubbyHole and available isn't true? The get method does nothing. Similarly, if the Producer called put before the Consumer got the value, put doesn't do anything.

You really want the Consumer to wait until the Producer puts something in the CubbyHole and the Producer notifies the Consumer when it's done so. Similarly, the Producer should wait until the Consumer takes a value (and notifies the Producer of its activities) before replacing it with a new value. The two threads must coordinate more fully and can use Object's wait and notifyAll methods to do so.

The following new get and put implementations wait on and notify each other of their activities.

public synchronized int get() { while (available == false) { try { //Wait for Producer to put value. wait(); } catch (InterruptedException e) { } } available = false; //Notify Producer that value has been retrieved. notifyAll();

Page 97: Java Interview

return contents;}

public synchronized void put(int value) { while (available == true) { try { //Wait for Consumer to get value. wait(); } catch (InterruptedException e) { } } contents = value; available = true; //Notify Consumer that value has been set. notifyAll();}The code in the get method loops until the Producer has produced a new value. Each time through the loop, get calls the wait method. The wait method relinquishes the lock on the CubbyHole held by the Consumer (thereby allowing the Producer to get the lock and update the CubbyHole) and then waits for notification from the Producer. When the Producer puts something in the CubbyHole, it notifies Consumer by calling notifyAll. The Consumer then comes out of the wait state and the get method returns the value in the CubbyHole.

The put method works in a similar fashion. It waits for the Consumer thread to consume the current value before allowing the Producer to produce a new one.

The notifyAll method wakes up all threads waiting on the object in question (in this case, the CubbyHole). The awakened threads compete for the lock. One thread gets it, and the others go back to waiting. The Object class also defines the notify method, which arbitrarily wakes up one of the threads waiting on this object.

The following are the three versions of the wait method contained in the Object class:

wait(): waits indefinitely for notification. (This method was used in the producer-consumer example.)

wait(long timeout): waits for notification or until the timeout period has elapsed; timeout is measured in milliseconds.

wait(long timeout, int nanos): waits for notification or until timeout milliseconds plus nanos nanoseconds have elapsed.

Note:  Besides using these timed wait methods to synchronize threads, you also can use them in place of sleep. Both wait and sleep delay for the requested amount of time. You can easily wake up wait with a notify, but a sleeping thread cannot be awakened

Page 98: Java Interview

prematurely. This doesn't matter too much for threads that don't sleep for long, but it could be important for threads that sleep for minutes at a time.

Thread Pools

A thread pool is a managed collection of threads that are available to perform tasks. Thread pools usually provide the following:

Improved performance when executing large numbers of tasks as a result of reduced per-task invocation overhead.

A way of bounding the resources, including threads, consumed when executing a collection of tasks.

In addition, thread pools relieve you from having to manage the life cycle of threads. They allow to take advantage of threading, but focus on the tasks that you want the threads to perform instead of thread mechanics.

To use thread pools, instantiate an implementation of the ExecutorService interface and hand it a set of tasks. The choices of configurable thread pool implementations are ThreadPoolExecutor and ScheduledThreadPoolExecutor . These implementations allow you to set the core and maximum pool size, the type of data structure used to hold the tasks, the way to handle rejected tasks, and the way to create and terminate threads. However, we recommend using the more convenient factory methods of the Executors class listed in the following table. These methods preconfigure settings for the most common usage scenarios.

Factory Methods in the Executors Class

Method Description

newFixedThreadPool(int) Creates a fixed-size thread pool.

newCachedThreadPool Creates an unbounded thread pool with automatic thread reclamation.

newSingleThreadExecutor Creates a single background thread.

Here is a runnable task called WorkerThread . The task performs some work and then periodically reports what percent of the work it has completed. ########################################################################

Java Basics1.The Java interpreter is used for the execution of the source code.TrueFalseAns: a.2) On successful compilation a file with the class extension is created.a) True

Page 99: Java Interview

b) FalseAns: a.3) The Java source code can be created in a Notepad editor.a) Trueb) FalseAns: a.4) The Java Program is enclosed in a class definition.a) Trueb) FalseAns: a.5) What declarations are required for every Java application?Ans: A class and the main( ) method declarations.6) What are the two parts in executing a Java program and their purposes?Ans: Two parts in executing a Java program are:Java Compiler and Java Interpreter.The Java Compiler is used for compilation and the Java Interpreter is used for execution of the application.7) What are the three OOPs principles and define them?Ans : Encapsulation, Inheritance and Polymorphism are the three OOPs Principles.Encapsulation:Is the Mechanism that binds together code and the data it manipulates, and keeps both safe from outside interference and misuse.Inheritance:Is the process by which one object acquires the properties of another object.Polymorphism:Is a feature that allows one interface to be used for a general class of actions.8) What is a compilation unit?Ans : Java source code file.9) What output is displayed as the result of executing the following statement?System.out.println("// Looks like a comment.");a) // Looks like a comment b) The statement results in a compilation error c) Looks like a comment d) No output is displayedAns : a.10) In order for a source code file, containing the public class Test, to successfully compile, which of the following must be true?It must have a package statement It must be named Test.java It must import java.lang It must declare a public class named TestAns : b11) What are identifiers and what is naming convention?

Page 100: Java Interview

Ans : Identifiers are used for class names, method names and variable names. An identifier may be any descriptive sequence of upper case & lower case letters,numbers or underscore or dollar sign and must not begin with numbers.12) What is the return type of program’s main( ) method?Ans : void13) What is the argument type of program’s main( ) method?Ans : string array.14) Which characters are as first characters of an identifier?Ans : A – Z, a – z, _ ,$15) What are different comments?Ans : 1) // -- single line comment2) /* --*/ multiple line comment 3) /** --*/ documentation16) What is the difference between constructor method and method?Ans : Constructor will be automatically invoked when an object is created. Whereas method has to be call explicitly.17) What is the use of bin and lib in JDK?Ans : Bin contains all tools such as javac, applet viewer, awt tool etc., whereas Lib contains all packages and variables.  

Data types,variables and Arrays1) What is meant by variable?Ans: Variables are locations in memory that can hold values. Before assigning any value to a variable, it must be declared.2) What are the kinds of variables in Java? What are their uses?Ans: Java has three kinds of variables namely, the instance variable, the local variable and the class variable.Local variables are used inside blocks as counters or in methods as temporary variables and are used to store information needed by a single method.Instance variables are used to define attributes or the state of a particular object and are used to store information needed by multiple methods in the objects.Class variables are global to a class and to all the instances of the class and are useful for communicating between different objects of all the same class or keeping track of global states. 3) How are the variables declared?Ans: Variables can be declared anywhere in the method definition and can be initialized during their declaration.They are commonly declared before usage at the beginning of the definition. Variables with the same data type can be declared together. Local variables must be given a value before usage.4) What are variable types?Ans: Variable types can be any data type that java supports, which includes the eight primitive data types, the name of a class or interface and an array.5) How do you assign values to variables?

Page 101: Java Interview

Ans: Values are assigned to variables using the assignment operator =.6) What is a literal? How many types of literals are there?Ans: A literal represents a value of a certain type where the type describes how that value behaves.There are different types of literals namely number literals, character literals, boolean literals, string literals,etc.7) What is an array?Ans: An array is an object that stores a list of items.8) How do you declare an array?Ans: Array variable indicates the type of object that the array holds.Ex: int arr[];9) Java supports multidimensional arrays.a)Trueb)FalseAns: a.10) An array of arrays can be created.a)Trueb)FalseAns: a.11) What is a string?Ans: A combination of characters is called as string.12) Strings are instances of the class String.a)Trueb)FalseAns: a.13) When a string literal is used in the program, Java automatically creates instances of the string class.a)Trueb)FalseAns: a.14) Which operator is to create and concatenate string?Ans: Addition operator(+).15) Which of the following declare an array of string objects?String[ ] s; String [ ]s: String[ s]: String s[ ]:Ans : a, b and d16) What is the value of a[3] as the result of the following array declaration?1 2 3 4Ans : d17) Which of the following are primitive types?byte

Page 102: Java Interview

String integer FloatAns : a.18) What is the range of the char type?0 to 216

0 to 215

0 to 216-1 0 to 215-1Ans. d19) What are primitive data types?Ans : byte, short, int, long,float, double,Boolean,char20) What are default values of different primitive types?Ans : int - 0short - 0byte - 0long - 0 lfloat - 0.0 fdouble - 0.0 d boolean - falsechar - null21) Converting of primitive types to objects can be explicitly.a)Trueb)FalseAns: b.22) How do we change the values of the elements of the array?Ans : The array subscript expression can be used to change the values of the elements of the array.23) What is final varaible?Ans : If a variable is declared as final variable, then you can not change its value. It becomes constant.24) What is static variable?Ans : Static variables are shared by all instances of a class. 

Operators1) What are operators and what are the various types of operators available in Java?Ans: Operators are special symbols used in expressions.The following are the types of operators:Arithmetic operators,Assignment operators, Increment & Decrement operators, Logical operators, Biwise operators, Comparison/Relational operators and Conditional operators2) The ++ operator is used for incrementing and the -- operator is used for decrementing.a)Trueb)FalseAns: a.3) Comparison/Logical operators are used for testing and magnitude.a)True

Page 103: Java Interview

b)FalseAns: a.4) Character literals are stored as unicode characters.a)Trueb)FalseAns: a.5) What are the Logical operators?Ans: OR(|), AND(&), XOR(^) AND NOT(~).6) What is the % operator?Ans : % operator is the modulo operator or reminder operator. It returns the reminder of dividing the first operand by second operand.7) What is the value of 111 % 13?3 5 7 9 Ans : c.8) Is &&= a valid operator?Ans : No.9) Can a double value be cast to a byte?Ans : Yes10) Can a byte object be cast to a double value ?Ans : No. An object cannot be cast to a primitive value. 11) What are order of precedence and associativity?Ans : Order of precedence the order in which operators are evaluated in expressions.Associativity determines whether an expression is evaluated left-right or right-left.12) Which Java operator is right associativity?Ans : = operator.13) What is the difference between prefix and postfix of -- and ++ operators?Ans : The prefix form returns the increment or decrement operation and returns the value of the increment or decrement operation.The postfix form returns the current value of all of the expression and then performs the increment or decrement operation on that value.14) What is the result of expression 5.45 + "3.2"?The double value 8.6 The string ""8.6" The long value 8. The String "5.453.2"Ans : d15) What are the values of x and y ?x = 5; y = ++x; Ans : x = 6; y = 616) What are the values of x and z?x = 5; z = x++; Ans : x = 6; z = 5 

Page 104: Java Interview

Control Statements1) What are the programming constructs?Ans: a) Sequentialb) Selection -- if and switch statementsc) Iteration -- for loop, while loop and do-while loop2) class conditional {public static void main(String args[]) {int i = 20;int j = 55;int z = 0;z = i < j ? i : j; // ternary operatorSystem.out.println("The value assigned is " + z);}}What is output of the above program?Ans: The value assigned is 203) The switch statement does not require a break.a)Trueb)FalseAns: b.4) The conditional operator is otherwise known as the ternary operator.a)Trueb)FalseAns: a.5) The while loop repeats a set of code while the condition is false.a)Trueb)FalseAns: b.6) The do-while loop repeats a set of code atleast once before the condition is tested.a)Trueb)FalseAns: a. 7) What are difference between break and continue?Ans: The break keyword halts the execution of the current loop and forces control out of the loop.The continue is similar to break, except that instead of halting the execution of the loop, it starts the next iteration.8) The for loop repeats a set of statements a certain number of times until a condition is matched.a)Trueb)FalseAns: a.9) Can a for statement loop indefintely?Ans : Yes.10) What is the difference between while statement and a do statement/

Page 105: Java Interview

Ans : A while statement checks at the beginning of a loop to see whether the next loop iteration should occur.A do statement checks at the end of a loop to see whether the next iteration of a loop should occur. The do statement will always execute the body of a loop at least once.   

Introduction to Classes and Methods1) Which is used to get the value of the instance variables?Ans: Dot notation.2) The new operator creates a single instance named class and returns a reference to that object.a)Trueb)FalseAns: a.3) A class is a template for multiple objects with similar features.a)Trueb)FalseAns: a.4) What is mean by garbage collection?Ans: When an object is no longer referred to by any variable, Java automatically reclaims memory used by that object. This is known as garbage collection. 5) What are methods and how are they defined?Ans: Methods are functions that operate on instances of classes in which they are defined.Objects can communicate with each other using methods and can call methods in other classes.Method definition has four parts. They are name of the method, type of object or primitive type the method returns, a list of parameters and the body of the method. A method's signature is a combination of the first three parts mentioned above.6) What is calling method?Ans: Calling methods are similar to calling or referring to an instance variable. These methods are accessed using dot notation. Ex: obj.methodname(param1,param2)7) Which method is used to determine the class of an object?Ans: getClass( ) method can be used to find out what class the belongs to. This class is defined in the object class and is available to all objects. 8) All the classes in java.lang package are automatically imported whena program is compiled.a)Trueb)FalseAns: a.9) How can class be imported to a program?Ans: To import a class, the import keyword should be used as shown.;import classname;10) How can class be imported from a package to a program?Ans: import java . packagename . classname (or) import java.package name.*;11) What is a constructor?Ans: A constructor is a special kind of method that determines how an object is

Page 106: Java Interview

initialized when created.12) Which keyword is used to create an instance of a class?Ans: new.13) Which method is used to garbage collect an object?Ans: finalize ().14) Constructors can be overloaded like regular methods.a)Trueb)FalseAns: a.15) What is casting?Ans: Casting is bused to convert the value of one type to another.16) Casting between primitive types allows conversion of one primitive type to another.a)Trueb)FalseAns: a.17) Casting occurs commonly between numeric types.a)Trueb)FalseAns: a.18) Boolean values can be cast into any other primitive type.a)Trueb)FalseAns: b.19) Casting does not affect the original object or value.a)Trueb)FalseAns: a.20) Which cast must be used to convert a larger value into a smaller one?Ans: Explicit cast.21) Which cast must be used to cast an object to another class?Ans: Specific cast.22) Which of the following features are common to both Java & C++?A.The class declarationb.The access modifiersc.The encapsulation of data & methods with in objectsd.The use of pointersAns: a,b,c.23) Which of the following statements accurately describe the use of access modifiers within a class definition?a.They can be applied to both data & methodsb.They must precede a class's data variables or methodsc.They can follow a class's data variables or methodsd.They can appear in any ordere.They must be applied to data variables first and then to methodsAns: a,b,d.24) Suppose a given instance variable has been declared private.

Page 107: Java Interview

Can this instance variable be manipulated by methods out side its class?a.yesb.noAns: b.25) Which of the following statements can be used to describe a public method?a.It is accessible to all other classes in the hierarchyb.It is accessablde only to subclasses of its parent classc.It represents the public interface of its classd.The only way to gain access to this method is by calling one of the public classmethodsAns: a,c.26) Which of the following types of class members can be part of the internal part of a class?a.Public instance variablesb.Private instance variablesc.Public methodsd.Private methodsAns: b,d.27) You would use the ____ operator to create a single instance of a named class.a.newb.dotAns: a.28) Which of the following statements correctly describes the relation between an object and the instance variable it stores?a.Each new object has its own distinctive set of instance variablesb.Each object has a copy of the instance variables of its classc.the instance variable of each object are seperate from the variables of other objectsd.The instance variables of each object are stored together with the variables of other objectsAns: a,b,c.29) If no input parameters are specified in a method declaration then the declaration will include __.a.an empty set of paranthesesb.the term voidAns: a.30) What are the functions of the dot(.) operator?a.It enables you to access instance variables of any objects within a classb.It enables you to store values in instance variables of an object c.It is used to call object methodsd.It is to create a new objectAns: a,b,c.31) Which of the following can be referenced by this variable?a.The instance variables of a class onlyb.The methods of a class onlyc.The instance variables and methods of a class Ans: c.

Page 108: Java Interview

32) The this reference is used in conjunction with ___methods.a.staticb.non-staticAns: b.33) Which of the following operators are used in conjunction with the this and super references?a.The new operatorb.The instanceof operatorc.The dot operatorAns: c.34) A constructor is automatically called when an object is instantiateda. trueb. false Ans: a.35) When may a constructor be called without specifying arguments?a. When the default constructor is not calledb. When the name of the constructor differs from that of the classc. When there are no constructors for the classAns: c.36) Each class in java can have a finalizer methoda. trueb.falseAns: a.37) When an object is referenced, does this mean that it has been identified by the finalizer method for garbage collection?a.yesb.noAns: b.38) Because finalize () belongs to the java.lang.Object class, it is present in all ___.a.objectsb.classesc.methodsAns: b.39) Identify the true statements about finalization.a.A class may have only one finalize method b.Finalizers are mostly used with simple classesc.Finalizer overloading is not allowedAns: a,c.40) When you write finalize() method for your class, you are overriding a finalizer inherited from a super class.a.trueb.falseAns: a.41) Java memory management mechanism garbage collects objects which are no longer referenceda true

Page 109: Java Interview

b.falseAns: a.42) are objects referenced by a variable candidates for garbage collection when the variable goes out of scope?a yesb. noAns: a.43) Java's garbage collector runs as a ___ priority thread waiting for __priority threads to relinquish the processor.a.high b.lowAns: a,b.44) The garbage collector will run immediately when the system is out of memorya.true b.falseAns: a.45) You can explicitly drop a object reference by setting the value of a variable whose data type is a reference type to ___Ans: null46) When might your program wish to run the garbage collecter?a. before it enters a compute-intense section of codeb. before it enters a memory-intense section of codec. before objects are finalizedd. when it knows there will be some idle timeAns: a,b,d47) For externalizable objects the class is solely responsible for the external format of its contentsa.true b.falseAns: a48) When an object is stored, are all of the objects that are reachable from that object stored as well?a.trueb.falseAns: a49) The default__ of objects protects private and trancient data, and supports the __ of the classesa.evolutionb.encodingAns: b,a.50) Which are keywords in Java?a) NULLb) sizeofc) friendd) extendse) synchronized

Page 110: Java Interview

Ans : d and e 51) When must the main class and the file name coincide?Ans :When class is declared public.52) What are different modifiers?Ans : public, private, protected, default, static, trancient, volatile, final, abstract.53) What are access modifiers?Ans : public, private, protected, default.54) What is meant by "Passing by value" and " Passing by reference"?Ans : objects – pass by referrenceMethods - pass by value 55) Is a class a subclass of itself?Ans : A class is a subclass itself.56) What modifiers may be used with top-level class?Ans : public, abstract, final.57) What is an example of polymorphism?Inner class Anonymous classes Method overloading Method overridingAns : c 

Packages and interface1) What are packages ? what is use of packages ?Ans :The package statement defines a name space in which classes are stored.If you omit the package, the classes are put into the default package.Signature... package pkg;Use: * It specifies to which package the classes defined in a file belongs to. * Package is both naming and a visibility control mechanism.2) What is difference between importing "java.applet.Applet" and "java.applet.*;" ?Ans :"java.applet.Applet" will import only the class Applet from the package java.appletWhere as "java.applet.*" will import all the classes from java.applet package.3) What do you understand by package access specifier?Ans : public: Anything declared as public can be accessed from anywhere private: Anything declared in the private can’t be seen outside of its class.default: It is visible to subclasses as well as to other classes in the same package.4) What is interface? What is use of interface?Ans : It is similar to class which may contain method’s signature only but not bodies. Methods declared in interface are abstract methods. We can implement many interfaces on a class which support the multiple inheritance.5) Is it is necessary to implement all methods in an interface?Ans : Yes. All the methods have to be implemented.6) Which is the default access modifier for an interface method?Ans : public.7) Can we define a variable in an interface ?and what type it should be ?Ans : Yes we can define a variable in an interface. They are implicitly final and static.8) What is difference between interface and an abstract class?

Page 111: Java Interview

Ans : All the methods declared inside an Interface are abstract. Where as abstract class must have at least one abstract method and others may be concrete or abstract. In Interface we need not use the keyword abstract for the methods.9) By default, all program import the java.lang package.True/FalseAns : True10) Java compiler stores the .class files in the path specified in CLASSPATH environmental variable.True/FalseAns : False11) User-defined package can also be imported just like the standard packages.True/FalseAns : True12) When a program does not want to handle exception, the ______class is used.Ans : Throws13) The main subclass of the Exception class is _______ class.Ans : RuntimeException14) Only subclasses of ______class may be caught or thrown.Ans : Throwable15) Any user-defined exception class is a subclass of the _____ class.Ans : Exception16) The catch clause of the user-defined exception class should ______ itsBase class catch clause.Ans : Exception17) A _______ is used to separate the hierarchy of the class while declaring anImport statement.Ans : Package 18) All standard classes of Java are included within a package called _____.Ans : java.lang19) All the classes in a package can be simultaneously imported using ____.Ans : *20) Can you define a variable inside an Interface. If no, why? If yes, how?Ans.: YES. final and static21) How many concrete classes can you have inside an interface?Ans.: None22) Can you extend an interface?Ans.: Yes23) Is it necessary to implement all the methods of an interface while implementing the interface? Ans.: No24) If you do not implement all the methods of an interface while implementing , what specifier should you use for the class ?Ans.: abstract25) How do you achieve multiple inheritance in Java?Ans: Using interfaces.

Page 112: Java Interview

26) How to declare an interface example?Ans : access class classname implements interface.27) Can you achieve multiple interface through interface?a)True b) falseAns : a.28) Can variables be declared in an interface ? If so, what are the modifiers?Ans : Yes. final and static are the modifiers can be declared in an interface.29) What are the possible access modifiers when implementing interface methods?Ans : public.30) Can anonymous classes be implemented an interface?Ans : Yes.31) Interfaces can’t be extended.a)Trueb)FalseAns : b.32) Name interfaces without a method?Ans : Serializable, Cloneble & Remote.33) Is it possible to use few methods of an interface in a class ? If so, how?Ans : Yes. Declare the class as abstract.  

Exception Handling1) What is the difference between ‘throw’ and ‘throws’ ?And it’s application?Ans : Exceptions that are thrown by java runtime systems can be handled by Try and catch blocks. With throw exception we can handle the exceptions thrown by the program itself. If a method is capable of causing an exception that it does not handle, it must specify this behavior so the callers of the method can guard against that exception.2) What is the difference between ‘Exception’ and ‘error’ in java?Ans : Exception and Error are the subclasses of the Throwable class. Exception class is used for exceptional conditions that user program should catch. With exception class we can subclass to create our own custom exception.Error defines exceptions that are not excepted to be caught by you program. Example is Stack Overflow.3) What is ‘Resource leak’?Ans : Freeing up other resources that might have been allocated at the beginning of a method.4)What is the ‘finally’ block?Ans : 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.5) Can we have catch block with out try block? If so when?Ans : No. Try/Catch or Try/finally form a unit.6) What is the difference between the following statements?Catch (Exception e),

Page 113: Java Interview

Catch (Error err),Catch (Throwable t)Ans :7) What will happen to the Exception object after exception handling?Ans : It will go for Garbage Collector. And frees the memory.8) How many Exceptions we can define in ‘throws’ clause?Ans : We can define multiple exceptions in throws clause.Signature is..type method-name (parameter-list) throws exception-list9) The finally block is executed when an exception is thrown, even if no catch matches it.True/FalseAns : True10) The subclass exception should precede the base class exception when used within the catch clause.True/FalseAns : True11) Exceptions can be caught or rethrown to a calling method.True/FalseAns : True 12) The statements following the throw keyword in a program are not executed.True/FalseAns : True13) The toString ( ) method in the user-defined exception class is overridden.True/FalseAns : True 

MULTI THREADING1) What are the two types of multitasking?Ans : 1.process-based2.Thread-based2) What are the two ways to create the thread?Ans : 1.by implementing Runnable2.by extending Thread3) What is the signature of the constructor of a thread class?Ans : Thread(Runnable threadob,String threadName)4) What are all the methods available in the Runnable Interface?Ans : run()5) What is the data type for the method isAlive() and this method is available in which class?Ans : boolean, Thread 6) What are all the methods available in the Thread class?Ans : 1.isAlive()2.join()3.resume()4.suspend()5.stop()

Page 114: Java Interview

6.start()7.sleep()8.destroy()7) What are all the methods used for Inter Thread communication and what is the class in which these methods are defined?Ans :1. wait(),notify() & notifyall()2. Object class8) What is the mechanisam defind by java for the Resources to be used by only one Thread at a time?Ans : Synchronisation9) What is the procedure to own the moniter by many threads?Ans : not possible10) What is the unit for 1000 in the below statement?ob.sleep(1000)Ans : long milliseconds11) What is the data type for the parameter of the sleep() method?Ans : long12) What are all the values for the following level?max-priority min-prioritynormal-priorityAns : 10,1,513) What is the method available for setting the priority?Ans : setPriority()14) What is the default thread at the time of starting the program?Ans : main thread15) The word synchronized can be used with only a method.True/ FalseAns : False16) Which priority Thread can prompt the lower primary Thread?Ans : Higher Priority17) How many threads at a time can access a monitor?Ans : one18) What are all the four states associated in the thread?Ans : 1. new 2. runnable 3. blocked 4. dead19) The suspend()method is used to teriminate a thread?True /FalseAns : False20) The run() method should necessary exists in clases created as subclass of thread?True /FalseAns : True21) When two threads are waiting on each other and can't proceed the programe is said to be in a deadlock?True/False Ans : True22) Which method waits for the thread to die ?

Page 115: Java Interview

Ans : join() method 23) Which of the following is true?1) wait(),notify(),notifyall() are defined as final & can be called only from with in a synchronized method2) Among wait(),notify(),notifyall() the wait() method only throws IOException3) wait(),notify(),notifyall() & sleep() are methods of object class 1 2 3 1 & 2 1,2 & 3Ans : D24) Garbage collector thread belongs to which priority?Ans : low-priority25) What is meant by timeslicing or time sharing?Ans : Timeslicing is the method of allocating CPU time to individual threads in a priority schedule.26) What is meant by daemon thread? In java runtime, what is it's role?Ans : Daemon thread is a low priority thread which runs intermittently in the background doing the garbage collection operation for the java runtime system.

Inheritance1) What is the difference between superclass & subclass?Ans : A super class is a class that is inherited whereas subclass is a class that does the inheriting. 2) Which keyword is used to inherit a class?Ans : extends3) Subclasses methods can access superclass members/ attributes at all times?True/FalseAns : False 4) When can subclasses not access superclass members?Ans : When superclass is declared as private.5) Which class does begin Java class hierarchy?Ans : Object class6) Object class is a superclass of all other classes?True/FalseAns : True7) Java supports multiple inheritance?True/FalseAns : False8) What is inheritance?Ans : Deriving an object from an existing class. In the other words, Inheritance is the process of inheriting all the features from a class9) What are the advantages of inheritance?

Page 116: Java Interview

Ans : Reusability of code and accessibility of variables and methods of the superclass by subclasses.10) Which method is used to call the constructors of the superclass from the subclass?Ans : super(argument)11) Which is used to execute any method of the superclass from the subclass?Ans : super.method-name(arguments)12) Which methods are used to destroy the objects created by the constructor methods?Ans : finalize()13) What are abstract classes?Ans : Abstract classes are those for which instances can’t be created.14) What must a class do to implement an interface?Ans: It must provide all of the methods in the interface and identify the interface in its implements clause.15) Which methods in the Object class are declared as final?Ans : getClass(), notify(), notifyAll(), and wait()16) Final methods can be overridden.True/FalseAns : False17) Declaration of methods as final results in faster execution of the program?True/FalseAns: True18) Final variables should be declared in the beginning?True/FalseAns : True19) Can we declare variable inside a method as final variables? Why?Ans : Cannot because, local variable cannot be declared as final variables.20) Can an abstract class may be final?Ans : An abstract class may not be declared as final.21) Does a class inherit the constructors of it's super class?Ans: A class does not inherit constructors from any of it's super classes.22) What restrictions are placed on method overloading?Ans: Two methods may not have the same name and argument list but different return types.23) What restrictions are placed on method overriding?Ans : Overridden methods must have the same name , argument list , and return type. The overriding method may not limit the access of the method it overridees.The overriding method may not throw any exceptions that may not be thrown by the overridden method.24) What modifiers may be used with an inner class that is a member of an outer class?Ans : a (non-local) inner class may be declared as public, protected, private, static, final or abstract.25) How this() is used with constructors?Ans: this() is used to invoke a constructor of the same class26) How super() used with constructors?Ans : super() is used to invoke a super class constructor27) Which of the following statements correctly describes an interface?a)It's a concrete class

Page 117: Java Interview

b)It's a superclassc)It's a type of abstract classAns: c28) An interface contains __ methodsa)Non-abstractb)Implementedc)unimplementedAns:c

STRING HANDLINGWhich package does define String and StringBuffer classes? Ans : java.lang package.Which method can be used to obtain the length of the String? Ans : length( ) method.How do you concatenate Strings? Ans : By using " + " operator.Which method can be used to compare two strings for equality? Ans : equals( ) method.Which method can be used to perform a comparison between strings that ignores case differences? Ans : equalsIgnoreCase( ) method.What is the use of valueOf( ) method? Ans : valueOf( ) method converts data from its internal format into a human-readable form.What are the uses of toLowerCase( ) and toUpperCase( ) methods? Ans : The method toLowerCase( ) converts all the characters in a string from uppercase to lowercase. The method toUpperCase( ) converts all the characters in a string from lowercase to uppercase. Which method can be used to find out the total allocated capacity of a StrinBuffer? Ans : capacity( ) method.Which method can be used to set the length of the buffer within a StringBuffer object? Ans : setLength( ).What is the difference between String and StringBuffer? Ans : String objects are constants, whereas StringBuffer objects are not.String class supports constant strings, whereas StringBuffer class supports growable, modifiable strings.What are wrapper classes? Ans : Wrapper classes are classes that allow primitive types to be accessed as objects. Which of the following is not a wrapper class?String Integer Boolean CharacterAns : a.

Page 118: Java Interview

What is the output of the following program?public class Question {public static void main(String args[]) {String s1 = "abc";String s2 = "def";String s3 = s1.concat(s2.toUpperCase( ) );System.out.println(s1+s2+s3);}}abcdefabcdef abcabcDEFDEF abcdefabcDEF None of the aboveANS : c.Which of the following methods are methods of the String class?delete( ) append( ) reverse( ) replace( )Ans : d.Which of the following methods cause the String object referenced by s to be changed?s.concat( ) s.toUpperCase( ) s.replace( ) s.valueOf( )Ans : a and b.String is a wrapper class?True FalseAns : b.17) If you run the code below, what gets printed out? String s=new String("Bicycle"); int iBegin=1; char iEnd=3; System.out.println(s.substring(iBegin,iEnd));Bic ic c) icy d) error: no method matching substring(int,char)Ans : b.18) Given the following declarations String s1=new String("Hello") String s2=new String("there"); String s3=new String();Which of the following are legal operations? s3=s1 + s2;

Page 119: Java Interview

s3=s1 - s2; c) s3=s1 & s2 d) s3=s1 && s2 Ans : a.19) Which of the following statements are true? The String class is implemented as a char array, elements are addressed using the stringname[] convention b) Strings are a primitive type in Java that overloads the + operator for concatenation c) Strings are a primitive type in Java and the StringBuffer is used as the matching wrapper type d) The size of a string can be retrieved using the length property.Ans : b. 

EXPLORING JAVA.LANG java.lang package is automatically imported into all programs.True FalseAns : aWhat are the interfaces defined by java.lang? Ans : Cloneable, Comparable and Runnable.What are the constants defined by both Flaot and Double classes? Ans : MAX_VALUE,MIN_VALUE,NaN,POSITIVE_INFINITY,NEGATIVE_INFINITY andTYPE.What are the constants defined by Byte, Short, Integer and Long? Ans : MAX_VALUE,MIN_VALUE and TYPE.What are the constants defined by both Float and Double classes? Ans : MAX_RADIX,MIN_RADIX,MAX_VALUE,MIN_VALUE and TYPE.What is the purpose of the Runtime class? Ans : The purpose of the Runtime class is to provide access to the Java runtime system.What is the purpose of the System class? Ans : The purpose of the System class is to provide access to system resources.Which class is extended by all other classes? Ans : Object class is extended by all other classes.Which class can be used to obtain design information about an object? Ans : The Class class can be used to obtain information about an object’s design.Which method is used to calculate the absolute value of a number?

Page 120: Java Interview

Ans : abs( ) method.What are E and PI? Ans : E is the base of the natural logarithm and PI is the mathematical value pi.Which of the following classes is used to perform basic console I/O?System SecurityManager Math RuntimeAns : a.Which of the following are true?The Class class is the superclass of the Object class. The Object class is final. The Class class can be used to load other classes. The ClassLoader class can be used to load other classes.Ans : c and d.Which of the following methods are methods of the Math class?absolute( ) log( ) cosine( ) sine( )Ans : b.Which of the following are true about the Error and Exception classes?Both classes extend Throwable. The Error class is final and the Exception class is not. The Exception class is final and the Error is not. Both classes implement Throwable.Ans : a.Which of the following are true?The Void class extends the Class class. The Float class extends the Double class. The System class extends the Runtime class. The Integer class extends the Number class. Ans : d.17) Which of the following will output -4.0 System.out.println(Math.floor(-4.7)); System.out.println(Math.round(-4.7)); System.out.println(Math.ceil(-4.7)); d) System.out.println(Math.Min(-4.7)); Ans : c.18) Which of the following are valid statements a) public class MyCalc extends Math b) Math.max(s); c) Math.round(9.99,1); d) Math.mod(4,10); e) None of the above.Ans : e.

Page 121: Java Interview

19) What will happen if you attempt to compile and run the following code? Integer ten=new Integer(10); Long nine=new Long (9);System.out.println(ten + nine); int i=1;System.out.println(i + ten);19 followed by 20 19 followed by 11 Error: Can't convert java lang Integer d) 10 followed by 1Ans : c. 

INPUT / OUTPUT : EXPLORING JAVA.IOWhat is meant by Stream and what are the types of Streams and classes of the Streams? Ans : A Stream is an abstraction that either produces or consumes information.There are two types of Streams. They are:Byte Streams : Byte Streams provide a convenient means for handling input and output of bytes. Character Streams : Character Streams provide a convenient means for handling input and output of characters.Byte Stream classes : Byte Streams are defined by using two abstract classes. They are:InputStream and OutputStream.Character Stream classes : Character Streams are defined by using two abstract classes. They are : Reader and Writer. Which of the following statements are true?UTF characters are all 8-bits. UTF characters are all 16-bits. UTF characters are all 24-bits. Unicode characters are all 16-bits. Bytecode characters are all 16-bits.Ans : d.Which of the following statements are true?When you construct an instance of File, if you do not use the filenaming semantics of the local machine, the constructor will throw an IOException. When you construct an instance of File, if the corresponding file does not exist on the local file system, one will be created. When an instance of File is garbage collected, the corresponding file on the local file system is deleted. None of the above.Ans : a,b and c.The File class contains a method that changes the current working directory.True FalseAns : b.It is possible to use the File class to list the contents of the current working directory.True

Page 122: Java Interview

FalseAns : a.Readers have methods that can read and return floats and doubles.True FalseAns : b.You execute the code below in an empty directory. What is the result?File f1 = new File("dirname");File f2 = new File(f1, "filename");A new directory called dirname is created in the current working directory. A new directory called dirname is created in the current working directory. A new file called filename is created in directory dirname. A new directory called dirname and a new file called filename are created, both in the current working directory. A new file called filename is created in the current working directory. No directory is created, and no file is created.Ans : e. What is the difference between the Reader/Writer class hierarchy and the InputStream/OutputStream class hierarchy?Ans : The Reader/Writer class hierarchy is character-oriented and the InputStream/OutputStream class hierarchy is byte-oriented.What is an I/O filter? Ans : An I/O filter is an object that reads from one stream and writes to another, usually altering the data in some way as it is passed from one stream to another.What is the purpose of the File class? Ans : The File class is used to create objects that provide access to the files and directories of a local file system.What interface must an object implement before it can be written to a stream as an object? Ans : An object must implement the Serializable or Externalizable interface before it can be written to a stream as an object.What is the difference between the File and RandomAccessFile classes? Ans : The File class encapsulates the files and directories of the local file system. The RandomAccessFile class provides the methods needed to directly access data contained in any part of a file.What class allows you to read objects directly from a stream? Ans : The ObjectInputStream class supports the reading of objects from input streams.What value does read( ) return when it has reached the end of a file? Ans : The read( ) method returns – 1 when it has reached the end of a file.What value does readLine( ) return when it has reached the end of a file? Ans : The readLine( ) method returns null when it has reached the end of a file.How many bits are used to represent Unicode, ASCII, UTF-16 and UTF-8 characters? Ans : Unicode requires 16-bits and ASCII requires 8-bits. Although the ASCII character set uses only 1-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.Which of the following are true?

Page 123: Java Interview

The InputStream and OutputStream classes are byte-oriented. The ObjectInputStream and ObjectOutputStream do not support serialized object input and output. The Reader and Writer classes are character-oriented. The Reader and Writer classes are the preferred solution to serialized object output.Ans : a and c.Which of the following are true about I/O filters?Filters are supported on input, but not on output. Filters are supported by the InputStream/OutputStream class hierarchy, but not by the Reader/Writer class hierarchy. Filters read from one stream and write to another. A filter may alter data that is read from one stream and written to another.Ans : c and d.Which of the following are true?Any Unicode character is represented using 16-bits. 7-bits are needed to represent any ASCII character. UTF-8 characters are represented using only 8-bits. UTF-16 characters are represented using only 16-bits.Ans : a and b.Which of the following are true?The Serializable interface is used to identify objects that may be written to an output stream. The Externalizable interface is implemented by classes that control the way in which their objects are serialized. The Serializable interface extends the Externalizable interface. The Externalizable interface extends the Serializable interface.Ans : a, b and d.Which of the following are true about the File class?A File object can be used to change the current working directory. A File object can be used to access the files in the current directory. When a File object is created, a corresponding directory or file is created in the local file system. File objects are used to access files and directories on the local file system. File objects can be garbage collected. When a File object is garbage collected, the corresponding file or directory is deleted.Ans : b, d and e. How do you create a Reader object from an InputStream object?Use the static createReader( ) method of InputStream class. Use the static createReader( ) method of Reader class. Create an InputStreamReader object, passing the InputStream object as an argument to the InputStreamReader constructor. Create an OutputStreamReader object, passing the InputStream object as an argument to the OutputStreamReader constructor.Ans : c.Which of the following are true?

Page 124: Java Interview

Writer classes can be used to write characters to output streams using different character encodings. Writer classes can be used to write Unicode characters to output streams. Writer classes have methods that support the writing of the values of any Java primitive type to output streams. Writer classes have methods that support the writing of objects to output streams.Ans : a and b.The isFile( ) method returns a boolean value depending on whether the file object is a file or a directory.True. False.Ans : a.Reading or writing can be done even after closing the input/output source.True. False.Ans : b.The ________ method helps in clearing the buffer. Ans : flush( ).The System.err method is used to print error message.True. False.Ans : a.What is meant by StreamTokenizer? Ans : StreamTokenizer breaks up InputStream into tokens that are delimited by sets of characters. It has the constructor : StreamTokenizer(Reader inStream).Here inStream must be some form of Reader.What is Serialization and deserialization?Ans : Serialization is the process of writing the state of an object to a byte stream.Deserialization is the process of restoring these objects. 30) Which of the following can you perform using the File class? a) Change the current directory b) Return the name of the parent directory c) Delete a file d) Find if a file contains text or binary informationAns : b and c.31)How can you change the current working directory using an instance of the File class called FileName?FileName.chdir("DirName"). FileName.cd("DirName"). FileName.cwd("DirName"). The File class does not support directly changing the current directory.Ans : d. 

EVENT HANDLING

Page 125: Java Interview

The event delegation model, introduced in release 1.1 of the JDK, is fully compatible with the event model.True FalseAns : b.A component subclass that has executed enableEvents( ) to enable processing of a certain kind of event cannot also use an adapter as a listener for the same kind of event.True FalseAns : b.What is the highest-level event class of the event-delegation model? Ans : The java.util.eventObject class is the highest-level class in the event-delegation hierarchy.What interface is extended by AWT event listeners? Ans : All AWT event listeners extend the java.util.EventListener interface.What class is the top of the AWT event hierarchy? Ans : The java.awt.AWTEvent class is the highest-level class in the AWT event class hierarchy.What event results from the clicking of a button? Ans : The ActionEvent event is generated as the result of the clicking of a button.What is the relationship between an event-listener interface and an event-adapter class? Ans : An event-listener interface defines the methods that must be implemented by an event handler for a particular kind of event.An event adapter provides a default implementation of an event-listener interface.In which package are most of the AWT events that support the event-delegation model defined? Ans : Most of the AWT–related events of the event-delegation model are defined in the java.awt.event package. The AWTEvent class is defined in the java.awt package.What is the advantage of the event-delegation model over the earlier event-inheritance model?Ans : The event-delegation has two advantages over the event-inheritance model. They are : It enables event handling by objects other than the ones that generate the events. This allows a clean separation between a component’s design and its use.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.What is the purpose of the enableEvents( ) method? Ans :The enableEvents( ) method is used to enable an event for a particular object.Which of the following are true?The event-inheritance model has replaced the event-delegation model. The event-inheritance model is more efficient than the event-delegation model.

Page 126: Java Interview

The event-delegation model uses event listeners to define the methods of event-handling classes. The event-delegation model uses the handleEvent( ) method to support event handling.Ans : c.Which of the following is the highest class in the event-delegation model?java.util.EventListener java.util.EventObject java.awt.AWTEvent java.awt.event.AWTEventAns : b.When two or more objects are added as listeners for the same event, which listener is first invoked to handle the event?The first object that was added as listener. The last object that was added as listener. There is no way to determine which listener will be invoked first. It is impossible to have more than one listener for a given event.Ans : c.Which of the following components generate action events?Buttons Labels Check boxes WindowsAns : a.Which of the following are true?A TextField object may generate an ActionEvent. A TextArea object may generate an ActionEvent. A Button object may generate an ActionEvent. A MenuItem object may generate an ActionEvent.Ans : a,c and d.Which of the following are true?The MouseListener interface defines methods for handling mouse clicks. The MouseMotionListener interface defines methods for handling mouse clicks. The MouseClickListener interface defines methods for handling mouse clicks. The ActionListener interface defines methods for handling the clicking of a button.Ans : a and d.Suppose that you want to have an object eh handle the TextEvent of a TextArea object t. How should you add eh as the event handler for t?t.addTextListener(eh); eh.addTextListener(t); addTextListener(eh.t); addTextListener(t,eh);Ans : a.What is the preferred way to handle an object’s events in Java 2?Override the object’s handleEvent( ) method. Add one or more event listeners to handle the events. Have the object override its processEvent( ) methods.

Page 127: Java Interview

Have the object override its dispatchEvent( ) methods.Ans : b.Which of the following are true?A component may handle its own events by adding itself as an event listener. A component may handle its own events by overriding its event-dispatching method. A component may not handle oits own events. A component may handle its own events only if it implements the handleEvent( ) method.Ans : a and b.

APPLETSWhat is an Applet? Should applets have constructors? Ans : Applet is a dynamic and interactive program that runs inside a Web page displayed by a Java capable browser. We don’t have the concept of Constructors in Applets. How do we read number information from my applet’s parameters, given that Applet’s getParameter() method returns a string? Ans : Use the parseInt() method in the Integer Class, the Float(String) constructor in the Class Float, or the Double(String) constructor in the class Double.How can I arrange for different applets on a web page to communicate with each other? Ans : Name your applets inside the Applet tag and invoke AppletContext’s getApplet() method in your applet code to obtain references to the other applets on the page.How do I select a URL from my Applet and send the browser to that page? Ans : Ask the applet for its applet context and invoke showDocument() on that context object.Eg. URL targetURL;String URLStringAppletContext context = getAppletContext();try{targetUR L = new URL(URLString);} catch (Malformed URLException e){// Code for recover from the exception }context. showDocument (targetURL);Can applets on different pages communicate with each other? Ans : No. Not Directly. The applets will exchange the information at one meeting place either on the local file system or at remote system.How do Applets differ from Applications? Ans : Appln: Stand AloneApplet: Needs no explicit installation on local m/c.Appln: Execution starts with main() method.Applet: Execution starts with init() method.Appln: May or may not be a GUIApplet: Must run within a GUI (Using AWT)How do I determine the width and height of my application? Ans : Use the getSize() method, which the Applet class inherits from the Component

Page 128: Java Interview

class in the Java.awt package. The getSize() method returns the size of the applet as a Dimension object, from which you extract separate width, height fields.Eg. Dimension dim = getSize ();int appletwidth = dim.width ();8) What is AppletStub Interface?Ans : The applet stub interface provides the means by which an applet and the browser communicate. Your code will not typically implement this interface.It is essential to have both the .java file and the .html file of an applet in the same directory.True. False.Ans : b.The <PARAM> tag contains two attributes namely _________ and _______. Ans : Name , value.Passing values to parameters is done in the _________ file of an applet.Ans : .html.12) What tags are mandatory when creating HTML to display an applet name, height, width code, name codebase, height, width d) code, height, width Ans : d.Applet’s getParameter( ) method can be used to get parameter values.True. False.Ans : a.What are the Applet’s Life Cycle methods? Explain them? Ans : init( ) method - Can be called when an applet is first loaded.start( ) method - Can be called each time an applet is started.paint( ) method - Can be called when the applet is minimized or refreshed.stop( ) method - Can be called when the browser moves off the applet’s page.destroy( ) method - Can be called when the browser is finished with the applet.What are the Applet’s information methods? Ans : getAppletInfo( ) method : Returns a string describing the applet, its author ,copy right information, etc.getParameterInfo( ) method : Returns an array of string describing the applet’s parameters. All Applets are subclasses of Applet.True. False.Ans : a.All Applets must import java.applet and java.awt.True. False.Ans : a.What are the steps involved in Applet development?

Page 129: Java Interview

Ans : a) Edit a Java source file,b) Compile your program andc) Execute the appletviewer, specifying the name of your applet’s source file.Applets are executed by the console based Java run-time interpreter.True. False.Ans : b.Which classes and interfaces does Applet class consist? Ans : Applet class consists of a single class, the Applet class and three interfaces: AppletContext, AppletStub and AudioClip.What is the sequence for calling the methods by AWT for applets?Ans : When an applet begins, the AWT calls the following methods, in this sequence.init( ) start( ) paint( ) When an applet is terminated, the following sequence of method cals takes place :stop( ) destroy( )Which method is used to output a string to an applet? Ans : drawString ( ) method.Every color is created from an RGB value.True. FalseAns : a.

AWT : WINDOWS, GRAPHICS AND FONTSHow would you set the color of a graphics context called g to cyan?g.setColor(Color.cyan); g.setCurrentColor(cyan); g.setColor("Color.cyan"); g.setColor("cyan’); g.setColor(new Color(cyan));Ans : a.The code below draws a line. What color is the line?g.setColor(Color.red.green.yellow.red.cyan);g.drawLine(0, 0, 100,100);Red Green Yellow Cyan BlackAns : d.What does the following code draw?g.setColor(Color.black);

Page 130: Java Interview

g.drawLine(10, 10, 10, 50);g.setColor(Color.RED);g.drawRect(100, 100, 150, 150);A red vertical line that is 40 pixels long and a red square with sides of 150 pixels A black vertical line that is 40 pixels long and a red square with sides of 150 pixels A black vertical line that is 50 pixels long and a red square with sides of 150 pixels A red vertical line that is 50 pixels long and a red square with sides of 150 pixels A black vertical line that is 40 pixels long and a red square with sides of 100 pixelAns : b.Which of the statements below are true?A polyline is always filled.b) A polyline can not be filled.c) A polygon is always filled.d) A polygon is always closede) A polygon may be filled or not filledAns : b, d and e.What code would you use to construct a 24-point bold serif font?new Font(Font.SERIF, 24,Font.BOLD); new Font("SERIF", 24, BOLD"); new Font("BOLD ", 24,Font.SERIF); new Font("SERIF", Font.BOLD,24); new Font(Font.SERIF, "BOLD", 24);Ans : d.What does the following paint( ) method draw?Public void paint(Graphics g) {g.drawString("question #6",10,0);}The string "question #6", with its top-left corner at 10,0 A little squiggle coming down from the top of the component, a little way in from the left edgeAns : b.What does the following paint( ) method draw?Public void paint(Graphics g) {g.drawString("question #6",10,0);}A circle at (100, 100) with radius of 44 A circle at (100, 44) with radius of 100 A circle at (100, 44) with radius of 44 The code does not compileAns : d.8)What is relationship between the Canvas class and the Graphics class?Ans : A Canvas object provides access to a Graphics object via its paint( ) method.What are the Component subclasses that support painting. Ans : The Canvas, Frame, Panel and Applet classes support painting.What is the difference between the paint( ) and repaint( ) method?

Page 131: Java Interview

Ans : The paint( ) method supports painting via a Graphics object. The repaint( ) method is used to cause paint( ) to be invoked by the AWT painting method. What is the difference between the Font and FontMetrics classes? Ans : The FontMetrics class is used to define implementation-specific properties, such as ascent and descent, of a Font object.Which of the following are passed as an argument to the paint( ) method?A Canvas object A Graphics object An Image object A paint objectAns : b.Which of the following methods are invoked by the AWT to support paint and repaint operations?paint( ) repaint( ) draw( ) redraw( )Ans : a.Which of the following classes have a paint( ) method?Canvas Image Frame Graphics Ans : a and c.Which of the following are methods of the Graphics class?drawRect( ) drawImage( ) drawPoint( ) drawString( )Ans : a, b and d.Which Font attributes are available through the FontMetrics class?ascent leading case heightAns : a, b and d.Which of the following are true?The AWT automatically causes a window to be repainted when a portion of a window has been minimized and then maximized. The AWT automatically causes a window to be repainted when a portion of a window has been covered and then uncovered. The AWT automatically causes a window to be repainted when application data is changed. The AWT does not support repainting operations.

Page 132: Java Interview

Ans : a and b.Which method is used to size a graphics object to fit the current size of the window? Ans : getSize( ) method.What are the methods to be used to set foreground and background colors?Ans : setForeground( ) and setBackground( ) methods.19) You have created a simple Frame and overridden the paint method as follows public void paint(Graphics g){ g.drawString("Dolly",50,10);}What will be the result when you attempt to compile and run the program? The string "Dolly" will be displayed at the centre of the frameb) An error at compilation complaining at the signature of the paint method c) The lower part of the word Dolly will be seen at the top of the form, with the top hidden. d) The string "Dolly" will be shown at the bottom of the form Ans : c.20) Where g is a graphics instance what will the following code draw on the screen. g.fillArc(45,90,50,50,90,180);a) An arc bounded by a box of height 45, width 90 with a centre point of 50,50, starting at an angle of 90 degrees traversing through 180 degrees counter clockwise.b) An arc bounded by a box of height 50, width 50, with a centre point of 45,90 starting at an angle of 90 degrees traversing through 180 degrees clockwise.c) An arc bounded by a box of height 50, width 50, with a top left at coordinates of 45, 90, starting at 90 degrees and traversing through 180 degrees counter clockwise.d) An arc starting at 45 degrees, traversing through 90 degrees clockwise bounded by a box of height 50, width 50 with a centre point of 90, 180.Ans : c.21) Given the following code import java.awt.*;public class SetF extends Frame{public static void main(String argv[]){SetF s = new SetF();s.setSize(300,200);s.setVisible(true);}} How could you set the frame surface color to pinka)s.setBackground(Color.pink);b)s.setColor(PINK);c)s.Background(pink);d)s.color=Color.pinkAns : a.AWT: CONTROLS, LAYOUT MANAGERS AND MENUSWhat is meant by Controls and what are different types of controls?Ans : Controls are componenets that allow a user to interact with your application.The AWT supports the following types of controls:

Page 133: Java Interview

Labels Push buttons Check boxes Choice lists Lists Scroll bars Text componentsThese controls are subclasses of Component.You want to construct a text area that is 80 character-widths wide and 10 character-heights tall. What code do you use?new TextArea(80, 10) new TextArea(10, 80)Ans: b.A text field has a variable-width font. It is constructed by calling new TextField("iiiii"). What happens if you change the contents of the text field to "wwwww"? (Bear in mind that is one of the narrowest characters, and w is one of the widest.)The text field becomes wider. The text field becomes narrower. The text field stays the same width; to see the entire contents you will have to scroll by using the ß and à keys. The text field stays the same width; to see the entire contents you will have to scroll by using the text field’s horizontal scroll bar.Ans : c. The CheckboxGroup class is a subclass of the Component class.True FalseAns : b.5) What are the immediate super classes of the following classes?a) Container class b) MenuComponent class c) Dialog class d) Applet class e) Menu classAns : a) Container - Component b) MenuComponent - Object c) Dialog - Window d) Applet - Panele) Menu - MenuItem6) What are the SubClass of Textcomponent Class?Ans : TextField and TextArea7) Which method of the component class is used to set the position and the size of a component?Ans : setBounds()8) Which TextComponent method is used to set a TextComponent to the read-only state?Ans : setEditable()

Page 134: Java Interview

9) How can the Checkbox class be used to create a radio button?Ans : By associating Checkbox objects with a CheckboxGroup.10) What Checkbox method allows you to tell if a Checkbox is checked?Ans : getState()11) Which Component method is used to access a component's immediate Container?getVisible() getImmediate getParent() getContainerAns : c.12) What methods are used to get and set the text label displayed by a Button object?Ans : getLabel( ) and setLabel( )13) What is the difference between a Choice and a List?Ans : A Choice is displayed in a compact form that requires you to pull it down to see the list of available choices. Only one item may be selected from a Choice.A List may be displayed in such a way that several List items are visible. A List supports the selection of one or more List items.14) Which Container method is used to cause a container to be laid out and redisplayed?Ans : validate( )15) What is the difference between a Scollbar and a Scrollpane?Ans : A Scrollbar is a Component, but not a Container.A Scrollpane is a Container and handles its own events and performs its own scrolling.16) Which Component subclass is used for drawing and painting?Ans : Canvas.17) Which of the following are direct or indirect subclasses of Component?Button Label CheckboxMenuItem Toolbar FrameAns : a, b and e.18) Which of the following are direct or indirect subclasses of Container?Frame TextArea MenuBar FileDialog AppletAns : a,d and e.19) Which method is used to set the text of a Label object?setText( ) setLabel( ) setTextLabel( ) setLabelText( )Ans : a.20) Which constructor creates a TextArea with 10 rows and 20 columns?

Page 135: Java Interview

new TextArea(10, 20) new TextArea(20, 10) new TextArea(new Rows(10), new columns(20)) new TextArea(200)Ans : a.(Usage is TextArea(rows, columns)21) Which of the following creates a List with 5 visible items and multiple selection enabled?new List(5, true) new List(true, 5) new List(5, false) new List(false,5)Ans : a.[Usage is List(rows, multipleMode)]22) Which are true about the Container class?The validate( ) method is used to cause a Container to be laid out and redisplayed. The add( ) method is used to add a Component to a Container. The getBorder( ) method returns information about a Container’s insets. The getComponent( ) method is used to access a Component that is contained in a Container.Ans : a, b and d.23) Suppose a Panel is added to a Frame and a Button is added to the Panel. If the Frame’s font is set to 12-point TimesRoman, the Panel’s font is set to 10-point TimesRoman, and the Button’s font is not set, what font will be used to dispaly the Button’s label?12-point TimesRoman 11-point TimesRoman 10-point TimesRoman 9-point TimesRomanAns : c.A Frame’s background color is set to Color.Yellow, and a Button’s background color is to Color.Blue. Suppose the Button is added to a Panel, which is added to the Frame. What background color will be used with the Panel?Colr.Yellow Color.Blue Color.Green Color.White Ans : a.25) Which method will cause a Frame to be displayed?show( ) setVisible( ) display( ) displayFrame( )Ans : a and b.26) All the componenet classes and container classes are derived from _________ class.Ans : Object.

Page 136: Java Interview

27) Which method of the container class can be used to add components to a Panel.Ans : add ( ) method.28) What are the subclasses of the Container class?Ans : The Container class has three major subclasses. They are :Window Panel ScrollPane 29) The Choice component allows multiple selection.True. False. Ans : b.30) The List component does not generate any events.True. False. Ans : b.31) Which components are used to get text input from the user.Ans : TextField and TextArea.32) Which object is needed to group Checkboxes to make them exclusive?Ans : CheckboxGroup.33) Which of the following components allow multiple selections?Non-exclusive Checkboxes. Radio buttons. Choice. List. Ans : a and d.34) What are the types of Checkboxes and what is the difference between them?Ans : Java supports two types of Checkboxes. They are : Exclusive and Non-exclusive.In case of exclusive Checkboxes, only one among a group of items can be selected at a time. I f an item from the group is selected, the checkbox currently checked is deselected and the new selection is highlighted. The exclusive Checkboxes are also called as Radio buttons.The non-exclusive checkboxes are not grouped together and each one can be selected independent of the other. 35) What is a Layout Manager and what are the different Layout Managers available in java.awt and what is the default Layout manager for the panal and the panal subclasses?Ans: A layout Manager is an object that is used to organize components in a container.The different layouts available in java.awt are : FlowLayout, BorderLayout, CardLayout, GridLayout and GridBag Layout.The default Layout Manager of Panal and Panal sub classes is FlowLayout".36) Can I exert control over the size and placement of components in my interface?Ans : Yes. myPanal.setLayout(null);myPanal.setbounds(20,20,200,200);37) Can I add the same component to more than one container?Ans : No. Adding a component to a container automatically removes it from any previous parent(container).

Page 137: Java Interview

38) How do I specify where a window is to be placed?Ans : Use setBounds, setSize, or setLocation methods to implement this.setBounds(int x, int y, int width, int height)setBounds(Rectangle r)setSize(int width, int height)setSize(Dimension d)setLocation(int x, int y)setLocation(Point p) 39) How can we create a borderless window?Ans : Create an instance of the Window class, give it a size, and show it on the screen.eg. Frame aFrame = ......Window aWindow = new Window(aFrame);aWindow.setLayout(new FlowLayout());aWindow.add(new Button("Press Me"));aWindow.getBounds(50,50,200,200);aWindow.show();40) Can I create a non-resizable windows? If so, how?Ans: Yes. By using setResizable() method in class Frame.41) What is the default Layout Manager for the Window and Window subclasses (Frame,Dialog)? Ans : BorderLayout().42) How are the elements of different layouts organized?Ans : FlowLayout : The elements of a FlowLayout are organized in a top to bottom, left to right fashion.BorderLayout : The elements of a BorderLayout are organized at the borders (North, South, East and West) and the center of a container.CardLayout : The elements of a CardLayout are stacked, one on top of the other, like a deck of cards.GridLayout : The elements of a GridLayout are of equal size and are laid out using the square of a grid. GridBagLayout : The elements of a GridBagLayout are organized according to a grid.However, the elements are of different sizes and may occupy more than one row or column of the grid. In addition, the rows and columns may have different sizes. 43) Which containers use a BorderLayout as their default layout?Ans : The Window, Frame and Dialog classes use a BorderLayout as their default layout.44) Which containers use a FlowLayout as their default layout?Ans : The Panel and the Applet classes use the FlowLayout as their default layout.45) What is the preferred size of a component?Ans : The preferred size of a component size that will allow the component to display normally.46) Which method is method to set the layout of a container?startLayout( ) initLayout( ) layoutContainer( )

Page 138: Java Interview

setLayout( ) Ans : d.47) Which method returns the preferred size of a component?getPreferredSize( ) getPreferred( ) getRequiredSize( ) getLayout( ) Ans : a.48) Which layout should you use to organize the components of a container in a tabular form?CardLayout BorederLayout FlowLayout GridLayout Ans : d.An application has a frame that uses a Border layout manager. Why is it probably not a good idea to put a vertical scroll bar at North in the frame? The scroll bar’s height would be its preferred height, which is not likely to be enough. The scroll bar’s width would be the entire width of the frame, which would be much wider than necessary. Both a and b. Neither a nor b. There is no problem with the layout as described.Ans : c.What is the default layouts for a applet, a frame and a panel? Ans : For an applet and a panel, Flow layout is the default layout, whereas Border layout is default layout for a frame.If a frame uses a Grid layout manager and does not contain any panels, then all the components within the frame are the same width and height.True False.Ans : a.If a frame uses its default layout manager and does not contain any panels, then all the components within the frame are the same width and height.True False.Ans : b.With a Border layout manager, the component at Center gets all the space that is left over, after the components at North and South have been considered.True FalseAns : b.An Applet has its Layout Manager set to the default of FlowLayout. What code would be the correct to change to another Layout Manager? setLayoutManager(new GridLayout()); setLayout(new GridLayout(2,2));

Page 139: Java Interview

c) setGridLayout(2,2,)) d setBorderLayout(); Ans : b.55) How do you indicate where a component will be positioned using Flowlayout?a) North, South,East,Westb) Assign a row/column grid referencec) Pass a X/Y percentage parameter to the add methodd) Do nothing, the FlowLayout will position the componentAns :d.56) How do you change the current layout manager for a container?a) Use the setLayout methodb) Once created you cannot change the current layout manager of a componentc) Use the setLayoutManager methodd) Use the updateLayout methodAns :a.57)When using the GridBagLayout manager, each new component requires a new instance of the GridBagConstraints class. Is this statement true or false?a) trueb) falseAns : b.58) Which of the following statements are true? a)The default layout manager for an Applet is FlowLayout b) The default layout manager for an application is FlowLayout c) A layout manager must be assigned to an Applet before the setSize method is called d) The FlowLayout manager attempts to honor the preferred size of any componentsAns : a and d.59) Which method does display the messages whenever there is an item selection or deselection of the CheckboxMenuItem menu?Ans : itemStateChanged method.60) Which is a dual state menu item?Ans : CheckboxMenuItem.61) Which method can be used to enable/diable a checkbox menu item?Ans : setState(boolean).Which of the following may a menu contain?A separator A check box A menu A button A panelAns : a and c.Which of the following may contain a menu bar?A panel A frame An applet A menu bar A menu

Page 140: Java Interview

Ans : b64) What is the difference between a MenuItem and a CheckboxMenuItem?Ans : The CheckboxMenuItem class extends the MenuItem class to support a menu item that may be checked or unchecked.65) Which of the following are true?A Dialog can have a MenuBar. MenuItem extends Menu. A MenuItem can be added to a Menu. A Menu can be added to a Menu.Ans : c and d.

Which colour is used to indicate instance methods in the standard "javadoc" format documentation: 1) blue2) red3) purple4) orangeAnswer : 2explainIn JDK 1.1 the variabels, methods and constructors are colour coded to simplifytheir identification.endExplainWhat is the correct ordering for the import, class and package declarations when found in a single file? 1) package, import, class2) class, import, package3) import, package, class4) package, class, importAnswer : 1explainThis is my explanation for question 2endExplainWhich methods can be legally applied to a string object? (Multiple)1) equals(String)2) equals(Object)3) trim()4) round()5) toString()Answer : 1,2,3,5What is the parameter specification for the public static void main method? (multiple)1) String args []2) String [] args3) Strings args []4) String argsAnswer : 1,2

Page 141: Java Interview

What does the zeroth element of the string array passed to the public static void main method contain? (multiple)1) The name of the program2) The number of arguments3) The first argument if one is presentAnswer : 3Which of the following are Java keywords? (multiple)1) goto2) malloc3) extends4) FALSEAnswer : 3What will be the result of compiling the following code: public class Test {public static void main (String args []) {int age;age = age + 1;System.out.println("The age is " + age);}}1) Compiles and runs with no output2) Compiles and runs printing out The age is 13) Compiles but generates a runtime error4) Does not compile5) Compiles but generates a compile time errorAnswer : 4Which of these is the correct format to use to create the literal char value a? (multiple)1) 'a'2) "a"3) new Character(a)4) \000aAnswer : 1What is the legal range of a byte integral type? 1) 0 - 65, 5352) (-128) - 1273) (-32,768) - 32,7674) (-256) - 255Answer : 2Which of the following is illegal: 1) int i = 32;2) float f = 45.0;3) double d = 45.0;Answer 2

Page 142: Java Interview

What will be the result of compiling the following code: public class Test {static int age;public static void main (String args []) {age = age + 1;System.out.println("The age is " + age);}}1) Compiles and runs with no output2) Compiles and runs printing out The age is 13) Compiles but generates a runtime error4) Does not compile5) Compiles but generates a compile time errorAnswer : 2Which of the following are correct? (multiple)1) 128 >> 1 gives 642) 128 >>> 1 gives 643) 128 >> 1 gives -644) 128 >>> 1 gives -64Answer : 1Which of the following return true? (multiple)1) "john" == new String("john")2) "john".equals("john")3) "john" = "john"4) "john".equals(new Button("john"))Answer : 2Which of the following do not lead to a runtime error? (multiple)1) "john" + " was " + " here"2) "john" + 33) 3 + 54) 5 + 5.5answer 1,2,3,4Which of the following are so called "short circuit" logical operators? (multiple)1) &2) ||3) &&4) |Answer : 2,3Which of the following are acceptable? (multiple)1) Object o = new Button("A");2) Boolean flag = true;

Page 143: Java Interview

3) Panel p = new Frame();4) Frame f = new Panel();5) Panel p = new Applet();Answer : 1,5What is the result of compiling and running the following code: public class Test {static int total = 10;public static void main (String args []) {new Test();}public Test () {System.out.println("In test");System.out.println(this);int temp = this.total;if (temp > 5) {System.out.println(temp);}}}(multiple)1) The class will not compile2) The compiler reports and error at line 23) The compiler reports an error at line 94) The value 10 is one of the elements printed to the standard output5) The class compiles but generates a runtime errorAnswer : 4Which of the following is correct: 1) String temp [] = new String {"j" "a" "z"};2) String temp [] = { "j " " b" "c"};3) String temp = {"a", "b", "c"};4) String temp [] = {"a", "b", "c"};Answer 4What is the correct declaration of an abstract method that is intended to be public: 1) public abstract void add();2) public abstract void add() {}3) public abstract add();4) public virtual add();Answer : 1Under what situations do you obtain a default constructor? 1) When you define any class2) When the class has no other constructors3) When you define at least one constructorAnswer : 2Which of the following can be used to define a constructor for this class, given the following code: public class Test {

Page 144: Java Interview

...}1) public void Test() {...}2) public Test() {...}3) public static Test() {...}4) public static void Test() {...}Answer : 2Which of the following are acceptable to the Java compiler: (multiple)1) if (2 == 3) System.out.println("Hi");2) if (2 = 3) System.out.println("Hi");3) if (true) System.out.println("Hi");4) if (2 != 3) System.out.println("Hi");5) if (aString.equals("hello")) System.out.println("Hi");Answer : 1,3,4,5Assuming a method contains code which may raise an Exception (but not a RuntimeException), what is the correct way for a method to indicate that it expects the caller to handle that exception: 1) throw Exception2) throws Exception3) new Exception4) Don't need to specify anythingAnswer : 2What is the result of executing the following code, using the parameters 4 and 0: public void divide(int a, int b) {try {int c = a / b;} catch (Exception e) {System.out.print("Exception ");} finally {System.out.println("Finally");}1) Prints out: Exception Finally2) Prints out: Finally3) Prints out: Exception4) No outputAnswer : 1Which of the following is a legal return type of a method overloading the following method: public void add(int a) {...}1) void2) int3) Can be anythingAnswer : 3Which of the following statements is correct for a method which is overriding the following method:

Page 145: Java Interview

public void add(int a) {...}1) the overriding method must return void2) the overriding method must return int3) the overriding method can return whatever it likesAnswer : 1Given the following classes defined in separate files, what will be the effect of compiling and running this class Test? class Vehicle {public void drive() {System.out.println("Vehicle: drive");}}class Car extends Vehicle {public void drive() {System.out.println("Car: drive");}}public class Test {public static void main (String args []) {Vehicle v;Car c;v = new Vehicle();c = new Car();v.drive();c.drive();v = c;v.drive();}}1) Generates a Compiler error on the statement v= c;2) Generates runtime error on the statement v= c;3) Prints out:Vehicle: driveCar: driveCar: drive4) Prints out: Vehicle: driveCar: driveVehicle: driveAnswer : 3Where in a constructor, can you place a call to a constructor defined in the super class? 1) Anywhere2) The first statement in the constructor3) The last statement in the constructor4) You can't call super in a constructorAnswer : 2

Page 146: Java Interview

Which variables can an inner class access from the class which encapsulates it? (multiple)1) All static variables2) All final variables3) All instance variables4) Only final instance variables5) Only final static variablesAnswer : 1,2,3What class must an inner class extend: 1) The top level class2) The Object class3) Any class or interface4) It must extend an interfaceAnswer 3In the following code, which is the earliest statement, where the object originally held in e, may be garbage collected: 1. public class Test {2. public static void main (String args []) {3. Employee e = new Employee("Bob", 48);4. e.calculatePay();5. System.out.println(e.printDetails());6. e = null;7. e = new Employee("Denise", 36);8. e.calculatePay();9. System.out.println(e.printDetails());10. }11. }1) Line 102) Line 113) Line 74) Line 85) NeverAnswer : 3What is the name of the interface that can be used to define a class that can execute within its own thread? 1) Runnable2) Run3) Threadable4) Thread5) ExecutableAnswer : 1What is the name of the method used to schedule a thread for execution? 1) init();2) start();3) run();4) resume();

Page 147: Java Interview

5) sleep();Answer : 2Which methods may cause a thread to stop executing? (multiple)1) sleep();2) stop();3) yield();4) wait();5) notify();6) notifyAll()7) synchronized()Answer : 1,2,3,4Which of the following would create a text field able to display 10 characters (assuming a fixed size font) displaying the initial string "hello": 1) new TextField("hello", 10);2) new TextField("hello");3) new textField(10);4) new TextField();Answer : 1Which of the following methods are defined on the Graphics class: (multiple)1) drawLine(int, int, int, int)2) drawImage(Image, int, int, ImageObserver)3) drawString(String, int, int)4) add(Component);5) setVisible(boolean);6) setLayout(Object);Answer : 1,2,3Which of the following layout managers honours the preferred size of a component: (multiple)1) CardLayout2) FlowLayout3) BorderLayout4) GridLayoutAnswer : 2Given the following code what is the effect of a being 5: public class Test {public void add(int a) {loop: for (int i = 1; i < 3; i++){for (int j = 1; j < 3; j++) {if (a == 5) {break loop;}System.out.println(i * j);}}

Page 148: Java Interview

}}1) Generate a runtime error2) Throw an ArrayIndexOutOfBoundsException3) Print the values: 1, 2, 2, 44) Produces no outputAnswer : 4What is the effect of issuing a wait() method on an object 1) If a notify() method has already been sent to that object then it has no effect2) The object issuing the call to wait() will halt until another object sends a notify() or notifyAll() method3) An exception will be raised4) The object issuing the call to wait() will be automatically synchronized with any other objects using the receiving object.Answer : 2The layout of a container can be altered using which of the following methods: (multiple)1) setLayout(aLayoutManager);2) addLayout(aLayoutManager);3) layout(aLayoutManager);4) setLayoutManager(aLayoutManager);Answer : 1Using a FlowLayout manager, which is the correct way to add elements to a container: 1) add(component);2) add("Center", component);3) add(x, y, component);4) set(component);Answer : 1Given that a Button can generate an ActionEvent which listener would you expect to have to implement, in a class which would handle this event? 1) FocusListener2) ComponentListener3) WindowListener4) ActionListener5) ItemListenerAnswer : 4Which of the following, are valid return types, for listener methods: 1) boolean2) the type of event handled3) void4) ComponentAnswer : 3Assuming we have a class which implements the ActionListener interface, which method should be used to register this with a Button? 1) addListener(*);2) addActionListener(*);

Page 149: Java Interview

3) addButtonListener(*);4) setListener(*);Answer : 2In order to cause the paint(Graphics) method to execute, which of the following is the most appropriate method to call: 1) paint()2) repaint()3) paint(Graphics)4) update(Graphics)5) None - you should never cause paint(Graphics) to executeAnswer : 2Which of the following illustrates the correct way to pass a parameter into an applet: 1) <applet code=Test.class age=33 width=100 height=100>2) <param name=age value=33>3) <applet code=Test.class name=age value=33 width=100 height=100>4) <applet Test 33>Answer : 2Which of the following correctly illustrate how an InputStreamReader can be created: (multiple)1) new InputStreamReader(new FileInputStream("data"));2) new InputStreamReader(new FileReader("data"));3) new InputStreamReader(new BufferedReader("data"));4) new InputStreamReader("data");5) new InputStreamReader(System.in);Answer : 1,5What is the permanent effect on the file system of writing data to a new FileWriter("report"), given the file report already exists? 1) The data is appended to the file2) The file is replaced with a new file3) An exception is raised as the file already exists4) The data is written to random locations within the fileAnswer : 2What is the effect of adding the sixth element to a vector created in the following manner: new Vector(5, 10);1) An IndexOutOfBounds exception is raised.2) The vector grows in size to a capacity of 10 elements3) The vector grows in size to a capacity of 15 elements4) Nothing, the vector will have grown when the fifth element was addedAnswer : 3What is the result of executing the following code when the value of x is 2: switch (x) {case 1:System.out.println(1);case 2:case 3:System.out.println(3);

Page 150: Java Interview

case 4:System.out.println(4);}1) Nothing is printed out2) The value 3 is printed out3) The values 3 and 4 are printed out4) The values 1, 3 and 4 are printed outAnswer : 3What is the result of compiling and running the Second class? Consider the following example:class First {public First (String s) {System.out.println(s);}}public class Second extends First {public static void main(String args []) {new Second();}}1) Nothing happens2) A string is printed to the standard out3) An instance of the class First is generated4) An instance of the class Second is created5) An exception is raised at runtime stating that there is no null parameter constructor in class First.6) The class second will not compile as there is no null parameter constructor in the class FirstAnswer : 6What is the result of executing the following fragment of code: boolean flag = false;if (flag = true) {System.out.println("true");} else {System.out.println("false");}1) true is printed to standard out2) false is printed to standard out3) An exception is raised4) Nothing happensAnswer : 1Consider the following classes. What is the result of compiling and running this class? public class Test {public static void test() {this.print();}

Page 151: Java Interview

public static void print() {System.out.println("Test");}public static void main(String args []) {test();}}(multiple)1) The string Test is printed to the standard out.2) A runtime exception is raised stating that an object has not been created.3) Nothing is printed to the standard output.4) An exception is raised stating that the method test cannot be found.5) An exception is raised stating that the variable this can only be used within an instance.6) The class fails to compile stating that the variable this is undefined.Answer : 6Examine the following class definition: public class Test {public static void test() {print();}public static void print() {System.out.println("Test");}public void print() {System.out.println("Another Test");}}What is the result of compiling this class:1) A successful compilation.2) A warning stating that the class has no main method.3) An error stating that there is a duplicated method.4) An error stating that the method test() will call one or other of the print() methods.Answer : 3What is the result of compiling and executing the following Java class: public class ThreadTest extends Thread {public void run() {System.out.println("In run");suspend();resume();System.out.println("Leaving run");}public static void main(String args []) {(new ThreadTest()).start();}}

Page 152: Java Interview

1) Compilation will fail in the method main.2) Compilation will fail in the method run.3) A warning will be generated for method run.4) The string "In run" will be printed to standard out.5) Both strings will be printed to standard out.6) Nothing will happen.Answer : 4Given the following sequence of Java statements, Which of the following options are true: 1. StringBuffer sb = new StringBuffer("abc");2. String s = new String("abc");3. sb.append("def");4. s.append("def");5. sb.insert(1, "zzz");6. s.concat(sb);7. s.trim();(multiple)1) The compiler would generate an error for line 1.2) The compiler would generate an error for line 2.3) The compiler would generate an error for line 3.4) The compiler would generate an error for line 4.5) The compiler would generate an error for line 5.6) The compiler would generate an error for line 6.7) The compiler would generate an error for line 7.Answer : 4,6What is the result of executing the following Java class: import java.awt.*;public class FrameTest extends Frame {public FrameTest() {add (new Button("First"));add (new Button("Second"));add (new Button("Third"));pack();setVisible(true);}public static void main(String args []) {new FrameTest();}}1) Nothing happens.2) Three buttons are displayed across a window.3) A runtime exception is generated (no layout manager specified).4) Only the "first" button is displayed.5) Only the "second" button is displayed.6) Only the "third" button is displayed.Answer : 6

Page 153: Java Interview

Consider the following tags and attributes of tags, which can be used with the <AAPLET> and </APPLET> tags? 1. CODEBASE2. ALT3. NAME4. CLASS5. JAVAC6. HORIZONTALSPACE7. VERTICALSPACE8. WIDTH9. PARAM10. JAR(multiple)1) line 1, 2, 32) line 2, 5, 6, 73) line 3, 4, 54) line 8, 9, 105) line 8, 9Answer : 1,5Which of the following is a legal way to construct a RandomAccessFile: 1) RandomAccessFile("data", "r");2) RandomAccessFile("r", "data");3) RandomAccessFile("data", "read");4) RandomAccessFile("read", "data");Answer : 1Carefully examine the following code, When will the string "Hi there" be printed? public class StaticTest {static {System.out.println("Hi there");}public void print() {System.out.println("Hello");}public static void main(String args []) {StaticTest st1 = new StaticTest();st1.print();StaticTest st2 = new StaticTest();st2.print();}}1) Never.2) Each time a new instance is created.3) Once when the class is first loaded into the Java virtual machine.4) Only when the static method is called explicitly.Answer : 3What is the result of the following program:

Page 154: Java Interview

public class Test {public static void main (String args []) {boolean a = false;if (a = true)System.out.println("Hello");elseSystem.out.println("Goodbye");}}1) Program produces no output but terminates correctly.2) Program does not terminate.3) Prints out "Hello"4) Prints out "Goodbye"Answer : 3Examine the following code, it includes an inner class, what is the result: public final class Test4 {class Inner {void test() {if (Test4.this.flag); {sample();}} }private boolean flag = true;public void sample() {System.out.println("Sample");}public Test4() {(new Inner()).test();}public static void main(String args []) {new Test4();} }1) Prints out "Sample"2) Program produces no output but terminates correctly.3) Program does not terminate.4) The program will not compileAnswer : 1Carefully examine the following class: public class Test5 {public static void main (String args []) {/* This is the start of a commentif (true) {Test5 = new test5();System.out.println("Done the test");

Page 155: Java Interview

}/* This is another comment */System.out.println ("The end");}}1) Prints out "Done the test" and nothing else.2) Program produces no output but terminates correctly.3) Program does not terminate.4) The program will not compile.5) The program generates a runtime exception.6) The program prints out "The end" and nothing else.7) The program prints out "Done the test" and "The end"Answer : 6What is the result of compiling and running the following applet: import java.applet.Applet;import java.awt.*;public class Sample extends Applet {private String text = "Hello World";public void init() {add(new Label(text));}public Sample (String string) {text = string;}}It is accessed form the following HTML page:<html><title>Sample Applet</title><body><applet code="Sample.class" width=200 height=200></applet></body></html>1) Prints "Hello World".2) Generates a runtime error.3) Does nothing.4) Generates a compile time error.Answer : 2What is the effect of compiling and (if possible) running this class:public class Calc {public static void main (String args []) {int total = 0;for (int i = 0, j = 10; total > 30; ++i, --j) {System.out.println(" i = " + i + " : j = " + j);total += (i + j);}System.out.println("Total " + total);

Page 156: Java Interview

}}1) Produce a runtime error2) Produce a compile time error3) Print out "Total 0"4) Generate the following as output:i = 0 : j = 10i = 1 : j = 9i = 2 : j = 8Total 30Answer : 3

Utility Package

1) What is the Vector class?ANSWER : The Vector class provides the capability to implement a growable array of objects.2) What is the Set interface?ANSWER : The Set interface provides methods for accessing the elements of a finite mathematical set.Sets do not allow duplicate elements.3) What is Dictionary class?ANSWER : The Dictionary class is the abstarct super class of Hashtable and Properties class.Dictionary provides the abstarct functions used to store and retrieve objects by key-value.This class allows any object to be used as a key or value.4) What is the Hashtable class?ANSWER : The Hashtable class implements a hash table data structure. A hash table indexes and stores objects in a dictionary using hash codes as the objects' keys. Hash codes are integer values that identify objects.5) What is the Properties class?Answer : 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 if a specified key is not found in the table. We have two methods load() and save().6) What changes are needed to make the following prg to compile?import java.util.*;class Ques{public static void main (String args[]) {String s1 = "abc";String s2 = "def";Vector v = new Vector();v.add(s1);v.add(s2);String s3 = v.elementAt(0) + v.elementAt(1);System.out.println(s3);}}ANSWER : Declare Ques as public B) Cast v.elementAt(0) to a String

Page 157: Java Interview

C) Cast v.elementAt(1) to an Object. D) Import java.langANSWER : B) Cast v.elementAt(0) to a String8) What is the output of the prg.import java.util.*;class Ques{public static void main (String args[]) {String s1 = "abc";String s2 = "def";Stack stack = new Stack(); stack.push(s1);stack.push(s2);try{String s3 = (String) stack.pop() + (String) stack.pop() ;System.out.println(s3);}catch (EmptyStackException ex){}}}ANSWER : abcdef B) defabc C) abcabc D) defdefANSWER : B) defabc9) Which of the following may have duplicate elements?ANSWER : Collection B) List C) Map D) SetANSWER : A and B Neither a Map nor a Set may have duplicate elements.10) Can null value be added to a List?ANSWER : Yes.A Null value may be added to any List.11) What is the output of the following prg.import java.util.*;class Ques{public static void main (String args[]) {HashSet set = new HashSet();String s1 = "abc";String s2 = "def";String s3 = "";set.add(s1);set.add(s2);set.add(s1);set.add(s2);Iterator i = set.iterator();while(i.hasNext()){s3 += (String) i.next();}System.out.println(s3);}}A) abcdefabcdef B) defabcdefabc C) fedcbafedcba D) defabcANSWER : D) defabc. Sets may not have duplicate elements.

Page 158: Java Interview

12) Which of the following java.util classes support internationalization?A) Locale B) ResourceBundle C) Country D) LanguageANSWER : A and B . Country and Language are not java.util classes.13) What is the ResourceBundle?The ResourceBundle class also supports internationalization.ResourceBundle subclasses are used to store locale-specific resources that can be loaded by a program to tailor the program's appearence to the paticular locale in which it is being run. Resource Bundles provide the capability to isolate a program's locale-specific resources in a standard and modular manner.14) How are Observer Interface and Observable class, in java.util package, used?ANSWER : Objects that subclass the Observable class maintain a list of Observers. When an Observable object is updated it invokes the update() method of each of its observers to notify the observers that it has changed state. The Observer interface is implemented by objects that observe Observable objects.15) Which java.util classes and interfaces support event handling?ANSWER : The EventObject class and the EventListener interface support event processing.16) Does java provide standard iterator functions for inspecting a collection of objects?ANSWER : The Enumeration interface in the java.util package provides a framework for stepping once through a collection of objects. We have two methods in that interface.public interface Enumeration {boolean hasMoreElements();Object nextElement();}17) The Math.random method is too limited for my needs- How can I generate random numbers more flexibly?ANSWER : The random method in Math class provide quick, convienient access to random numbers, but more power and flexibility use the Random class in the java.util package.double doubleval = Math.random();The Random class provide methods returning float, int, double, and long values.nextFloat() // type float; 0.0 <= value < 1.0nextDouble() // type double; 0.0 <= value < 1.0nextInt() // type int; Integer.MIN_VALUE <= value <= Integer.MAX_VALUEnextLong() // type long; Long.MIN_VALUE <= value <= Long.MAX_VALUEnextGaussian() // type double; has Gaussian("normal") distribution with mean 0.0 and standard deviation 1.0)Eg. Random r = new Random();float floatval = r.nextFloat();18) How can we get all public methods of an object dynamically?ANSWER : By using getMethods(). It return an array of method objects corresponding to the public methods of this class. getFields() returns an array of Filed objects corresponding to the public Fields(variables) of this class.

Page 159: Java Interview

getConstructors() returns an array of constructor objects corresponding to the public constructors of this class. JDBC1) What are the steps involved in establishing a connection?ANSWER : This involves two steps: (1) loading the driver and (2) making the connection. 2) How can you load the drivers?ANSWER : Loading the driver or drivers you want to use is very simple and involves just one line of code. If, for example, you want to use the JDBC-ODBC Bridge driver, the following code will load it:Eg.Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");Your driver documentation will give you the class name to use. For instance, if the class name is jdbc.DriverXYZ , you would load the driver with the following line of code:Eg.Class.forName("jdbc.DriverXYZ");3) What Class.forName will do while loading drivers?ANSWER : 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. 4) How can you make the connection?ANSWER : In establishing a connection is to have the appropriate driver connect to the DBMS. The following line of code illustrates the general idea:Eg.String url = "jdbc:odbc:Fred";Connection con = DriverManager.getConnection(url, "Fernanda", "J8");5) How can you create JDBC statements?ANSWER : A Statement object is what sends your SQL statement to the DBMS. You simply create a Statement object and then execute it, supplying the appropriate execute method with the SQL statement you want to send. For a SELECT statement, the method to use is executeQuery. For statements that create or modify tables, the method to use is executeUpdate.Eg.It takes an instance of an active connection to create a Statement object. In the following example, we use our Connection object con to create the Statement object stmt :Statement stmt = con.createStatement();6) How can you retrieve data from the ResultSet?ANSWER : Step 1.JDBC returns results in a ResultSet object, so we need to declare an instance of the class ResultSet to hold our results. The following code demonstrates declaring the ResultSet object rs.Eg.ResultSet rs = stmt.executeQuery("SELECT COF_NAME, PRICE FROM COFFEES");Step2.String s = rs.getString("COF_NAME");

Page 160: Java Interview

The method getString is invoked on the ResultSet object rs , so getString will retrieve (get) the value stored in the column COF_NAME in the current row of rs 7) What are the different types of Statements?ANSWER : 1.Statement (use createStatement method) 2. Prepared Statement (Use prepareStatement method) and 3. Callable Statement (Use prepareCall)8) How can you use PreparedStatement?ANSWER : This special type of statement is derived from the more general class, Statement.If you want to execute a Statement object many times, it will normally reduce execution time to use a PreparedStatement object instead.The advantage to this is that in most cases, this SQL statement will be sent to the DBMS right away, where it will be compiled. As a result, the PreparedStatement object contains not just an SQL statement, but an SQL statement that has been precompiled. This means that when the PreparedStatement is executed, the DBMS can just run the PreparedStatement 's SQL statement without having to compile it first. Eg.PreparedStatement updateSales = con.prepareStatement("UPDATE COFFEES SET SALES = ? WHERE COF_NAME LIKE ?");9) What setAutoCommit does?ANSWER : When a connection is created, it is in auto-commit mode. This means that each individual SQL statement is treated as a transaction and will be automatically committed right after it is executed. The way to allow two or more statements to be grouped into a transaction is to disable auto-commit modeEg.con.setAutoCommit(false);Once auto-commit mode is disabled, no SQL statements will be committed until you call the method commit explicitly. Eg.con.setAutoCommit(false);PreparedStatement updateSales = con.prepareStatement("UPDATE COFFEES SET SALES = ? WHERE COF_NAME LIKE ?");updateSales.setInt(1, 50);updateSales.setString(2, "Colombian");updateSales.executeUpdate();PreparedStatement updateTotal = con.prepareStatement("UPDATE COFFEES SET TOTAL = TOTAL + ? WHERE COF_NAME LIKE ?");updateTotal.setInt(1, 50);updateTotal.setString(2, "Colombian");updateTotal.executeUpdate();con.commit();con.setAutoCommit(true);10) How to call a Strored Procedure from JDBC?ANSWER : The first step is to create a CallableStatement object. As with Statement an and PreparedStatement objects, this is done with an open Connection object. A CallableStatement object contains a call to a stored procedure;Eg.CallableStatement cs = con.prepareCall("{call SHOW_SUPPLIERS}");

Page 161: Java Interview

ResultSet rs = cs.executeQuery();11) How to Retrieve Warnings?ANSWER : 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 objectEg.SQLWarning warning = stmt.getWarnings();if (warning != null) {System.out.println("\n---Warning---\n");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());System.out.println("");warning = warning.getNextWarning();}}12) How can you Move the Cursor in Scrollable Result Sets ?ANSWER : One of the new features in the JDBC 2.0 API is the ability to move a result set's cursor backward as well as forward. There are also methods that let you move the cursor to a particular row and check the position of the cursor. Eg.Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_READ_ONLY);ResultSet srs = stmt.executeQuery("SELECT COF_NAME, PRICE FROM COFFEES");The first argument is one of three constants added to the ResultSet API to indicate the type of a ResultSet object: TYPE_FORWARD_ONLY, TYPE_SCROLL_INSENSITIVE , and TYPE_SCROLL_SENSITIVE . The second argument is one of two ResultSet constants for specifying whether a result set is read-only or updatable: CONCUR_READ_ONLY and CONCUR_UPDATABLE . The point to remember here is that if you specify a type, you must also specify whether it is read-only or updatable. Also, you must specify the type first, and because both parameters are of type int , the compiler will not complain if you switch the order. Specifying the constant TYPE_FORWARD_ONLY creates a nonscrollable result set, that is, one in which the cursor moves only forward. If you do not specify any constants for the type and updatability of a ResultSet object, you will automatically get one that is TYPE_FORWARD_ONLY and CONCUR_READ_ONLY 13) What’s the difference between TYPE_SCROLL_INSENSITIVE , and TYPE_SCROLL_SENSITIVE?ANSWER : You will get a scrollable ResultSet object if you specify one of these ResultSet constants.The difference between the two has to do with whether a result set

Page 162: Java Interview

reflects changes that are made to it while it is open and whether certain methods can be called to detect these changes. Generally speaking, a result set that is TYPE_SCROLL_INSENSITIVE does not reflect changes made while it is still open and one that is TYPE_SCROLL_SENSITIVE does. All three types of result sets will make changes visible if they are closed and then reopenedEg.Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);ResultSet srs = stmt.executeQuery("SELECT COF_NAME, PRICE FROM COFFEES");srs.afterLast();while (srs.previous()) {String name = srs.getString("COF_NAME");float price = srs.getFloat("PRICE");System.out.println(name + " " + price);}14) How to Make Updates to Updatable Result Sets?ANSWER : Another new feature in the JDBC 2.0 API is the ability to update rows in a result set using methods in the Java programming language rather than having to send an SQL command. But before you can take advantage of this capability, you need to create a ResultSet object that is updatable. In order to do this, you supply the ResultSet constant CONCUR_UPDATABLE to the createStatement method.Eg.Connection con = DriverManager.getConnection("jdbc:mySubprotocol:mySubName");Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);ResultSet uprs = stmt.executeQuery("SELECT COF_NAME, PRICE FROM COFFEES"); 

Networking Concepts1) The API doesn't list any constructors for InetAddress- How do I create an InetAddress instance?ANSWER : In case of InetAddress the three methods getLocalHost, getByName, getByAllName can be used to create instances.E.g.InetAddress add1;InetAddress add2;try{add1 = InetAddress.getByName("java.sun.com");add2 = InetAddress.getByName("199.22.22.22");}catch(UnknownHostException e){}2) Is it possible to get the Local host IP?ANSWER : Yes. Use InetAddress's getLocalHost method.3) What's the Factory Method?ANSWER : Factory methods are merely a convention whereby static methods in a class return an instance of that class. The InetAddress class has no visible constructors. To create an InetAddress object, you have to use one of the available factory methods. In

Page 163: Java Interview

InetAddress the three methods getLocalHost, getByName, getByAllName can be used to create instances of InetAddress.4) What’s the difference between TCP and UDP?ANSWER : These two protocols differ in the way they carry out the action of communicating. A TCP protocol establishes a two way connection between a pair of computers, while the UDP protocol is a one-way message sender. The common analogy is that TCP is like making a phone call and carrying on a two-way communication, while UDP is like mailing a letter.5) What is the Proxy Server?ANSWER : A proxy server speaks the client side of a protocol to another server. This is often required when clients have certain restrictions on which servers they can connect to. And when several users are hitting a popular web site, a proxy server can get the contents of the web server's popular pages once, saving expensive internetwork transfers while providing faster access to those pages to the clients.Also, we can get multiple connections for a single server.6) What are the seven layers of OSI model?ANSWER : Application, Presentation, Session, Transport, Network, DataLink, Physical Layer.What Transport Layer does?ANSWER : It ensures that the mail gets to its destination. If a packet fails to get its destination, it handles the process of notifying the sender and requesting that another packet be sent.8) What is DHCP?ANSWER : Dynamic Host Configuration Protocol, a piece of the TCP/IP protocol suite that handles the automatic assignment of IP addresses to clients.9) What is SMTP?ANSWER : Simple Mail Transmission Protocol, the TCP/IP Standard for Internet mails. SMTP exchanges mail between servers; contrast this with POP, which transmits mail between a server and a client.10) In OSI N/w architecture, the dialogue control and token management are responsibilities of...Answer : Network b) Session c) Application d) DataLinkANSWER : b) Session Layer.11) In OSI N/W Architecture, the routing is performed by ______Answer : Network b) Session c) Application d) DataLinkANSWER : Answer : Network Layer.NetworkingWhat is the difference between URL instance and URLConnection instance?ANSWER : A URL instance represents the location of a resource, and a URLConnection instance represents a link for accessing or communicating with the resource at the location.2) How do I make a connection to URL?ANSWER : You obtain a URL instance and then invoke openConnection on it.URLConnection is an abstract class, which means you can't directly create instances of it using a constructor. We have to invoke openConnection method on a URL instance, to get the right kind of connection for your URL.

Page 164: Java Interview

Eg. URL url;URLConnection connection;try{ url = new URL("...");conection = url.openConnection();}catch (MalFormedURLException e) { }3) What Is a Socket?A socket is one end-point of a two-way communication link between two programs running on the network. A socket is bound to a port number so that the TCP layer can identify the application that data is destined to be sent.Socket classes are used to represent the connection between a client program and a server program. The java.net package provides two classes--Socket and ServerSocket--which implement the client side of the connection and the server side of the connection, respectively. What information is needed to create a TCP Socket? ANSWER : The Local System’s IP Address and Port Number.And the Remote System's IPAddress and Port Number.5) What are the two important TCP Socket classes?ANSWER : Socket and ServerSocket.ServerSocket is used for normal two-way socket communication. Socket class allows us to read and write through the sockets.getInputStream() and getOutputStream() are the two methods available in Socket class.When MalformedURLException and UnknownHostException throws?ANSWER : When the specified URL is not connected then the URL throw MalformedURLException and If InetAddress’ methods getByName and getLocalHost are unabletoresolve the host name they throwan UnknownHostException.

Servlets1) What is the servlet?ANSWER : Servlets are modules that extend request/response-oriented servers, such as Java-enabled web servers. For example, a servlet might be responsible for taking data in an HTML order-entry form and applying the business logic used to update a company's order database.Servlets are to servers what applets are to browsers. Unlike applets, however, servlets have no graphical user interface. 2) Whats the advantages using servlets than using CGI?ANSWER : Servlets provide a way to generate dynamic documents that is both easier to write and faster to run. Servlets also address the problem of doing server-side programming with platform-specific APIs: they are developed with the Java Servlet API, a standard Java extension. 3) What are the uses of Servlets?ANSWER : A servlet can handle multiple requests concurrently, and can synchronize requests. This allows servlets to support systems such as on-line conferencing. Servlets can forward requests to other servers and servlets.Thus servlets can be used to balance load among several servers that mirror the same content, and to partition a single logical service over several servers, according to task type or organizational boundaries. 4) Which pakage provides interfaces and classes for writing servlets?ANSWER : javax

Page 165: Java Interview

5) Whats the Servlet Interfcae?ANSWER : The central abstraction in the Servlet API is the Servlet interface. All servlets implement this interface, either directly or, more commonly, by extending a class that implements it such as HttpServlet.Servlets-->Generic Servlet-->HttpServlet-->MyServlet.The Servlet interface declares, but does not implement, methods that manage the servlet and its communications with clients. Servlet writers provide some or all of these methods when developing a servlet. 6) When a servlet accepts a call from a client, it receives two objects- What are they?ANSWER : ServeltRequest: Which encapsulates the communication from the client to the server.ServletResponse: Whcih encapsulates the communication from the servlet back to the client.ServletRequest and ServletResponse are interfaces defined by the javax.servlet package. 7) What information that the ServletRequest interface allows the servlet access to?ANSWER : Information such as the names of the parameters passed in by the client, the protocol (scheme) being used by the client, and the names of the remote host that made the request and the server that received it. The input stream, ServletInputStream.Servlets use the input stream to get data from clients that use application protocols such as the HTTP POST and PUT methods.8) What information that the ServletResponse interface gives the servlet methods for replying to the client? ANSWER : It Allows the servlet to set the content length and MIME type of the reply. Provides an output stream, ServletOutputStream and a Writer through which the servlet can send the reply data. 9) What is the servlet Lifecycle?ANSWER : Each servlet has the same life cycle: A server loads and initializes the servlet (init())The servlet handles zero or more client requests (service())The server removes the servlet (destroy())(some servers do this step only when they shut down) 10) How HTTP Servlet handles client requests?ANSWER : An HTTP Servlet handles client requests through its service method. The service method supports standard HTTP client requests by dispatching each request to a method designed to handle that request. 1Encapsulation : Encapsulation is the mechanism that binds together code and the data it manipulates and keeps both safe from outside interference and misuse.Inheritance: Inheritance is the process by which one object acquires the properties of another object.Polymorphism: Polymorphism is a feature that allows one interface to be used for a general class of actions. The specific action is determined by the exact nature of actions.Code Blocks:

Page 166: Java Interview

Two or more statements which is allowed to be grouped into blocks of code is otherwise called as Code Blocks.This is done by enclosing the statements between opening and closing curly braces.Floating-point numbers: Floating-point numbers which is also known as real numbers, are used when evaluating expressions that require fractional precision.Unicode: Unicode defines a fully international character set that can represent all of the characters found in all human languages. It is a unification of dozens of character sets, such as Latin, Greek, Arabic and many more.Booleans: Java has a simple type called boolean, for logical values. It can have only on of two possible values, true or false.Casting: A cast is simply an explicit type conversion. To create a conversion between two incompatible types, you must use a cast.Arrays: An array is a group of like-typed variables that are referred to by a common name. Arrays offer a convenient means of grouping related information. Arrays of any type can be created and may have one or more dimension.Relational Operators:The relational operators determine the relationship that one operand has to the other. They determine the equality and ordering.11.Short-Circuit Logical Operators:The secondary versions of the Boolean AND and OR operators are known as short- circuit logical operators. It is represented by || and &&..12. Switch:The switch statement is Java’s multiway branch statement. It provides an easy way to dispatch execution to different parts of your code based on the value of an experession.13. Jump Statements:Jump statements are the statements which transfer control to another part of your program. Java Supports three jump statements: break, continue, and return.14. Instance Variables:The data, or variable, defined within a class are called instance variable.