================================================================================== == | | url for the page is : http://www.geocities.com/binoymg/Java_Questions.

htm | | ================================================================================== =

100 Java Interview Questions and Answers Here is my collection of 100 java interview questions and answers. Hope this would be a great help for new and experienced programmers to refresh their technical knowledge. I would like to express my sincere thanks to Kamal, who helped me to make it successful. Expecting your valuable suggestions and comments. Binoy M. George

1.What's the difference between interface and abstract class? Which one you would prefer? In what situation would you use an abstract class? Interfaces are often used to describe the peripheral abilities of a class, not its central identity. An abstract class defines the core identity of its descendants. "heterogeneous vs. homogeneous." If implementers/subclasses are homogeneous, tend towards an abstract base class. If they are heterogeneous, use an interface. Abstract classes are excellent candidates inside of application frameworks. Abstract classes let you define some behaviors; they force your subclasses to provide others. 2. Why would you apply design patterns (benefits)? A pattern is a recurring solution to a standard problem. When related patterns are woven together they form a ``language'' that provides a process for the orderly resolution of software development problems. Pattern languages are not formal languages, but rather a collection of interrelated patterns, though they do provide a vocabulary for talking about a particular problem. Both patterns and pattern languages help developers communicate architectural knowledge, help people learn a new design paradigm or architectural style, and help new developers ignore traps and pitfalls that have traditionally been learned only by costly experience. http://www.mindspring.com/~mgrand/pattern_synopses.htm#Creational%20Patterns 3. Name 3 design patterns in the Java 2 API. Write a Singleton. In what situation would you use a Singleton? Singleton Pattern, Business Delegate, Value Object Singleton pattern Ensure a class only has one instance, and provide a global point of access to it. It�s important for some classes to have exactly one instance. Although there can be many printers in a system, there should be only one printer spooler. There should be only one file system (or file system manager) and one window manager.

public class Singleton { private static final Singleton INSTANCE = new Singleton(); // Private constructor supresses // default public constructor private Singleton( ) { } public static Singleton getInstance( ) { return INSTANCE; }

} If you want to make it serializable, then change the declaration to: public class Singleton implements Serializable and add this method: private Object readResolve() throws ObjectStreamException { return INSTANCE; } The readResolve method serves to prevent the release of multiple instances upon deserialization.

Another Implementation in the AppController Factory class /** * @return The unique instance of this class. */ static public AppControllerFactory instance() { if(null == _factory) { _factory = new AppControllerFactory(); } return _factory; } Business Delegate: In a normal scenario, presentation-tier components (e.g. a JSP) interact directly with business services. As a result, the presentation-tier components are vulnerable to changes in the implementation of the business services: when the implementation of the business services change, the code in the presentation tier must change. The goal of Business Delegate object design pattern is to minimize the coupling between presentation-tier clients and the business service API, thus hiding the underlying implementation details of the service. In this way we enhance the manageability of the application. Using this design pattern, the client request is first handled by a Servlet that dispatches to a JSP page for formatting and display. The JSP is responsible for delegating the processing of business functionality to a "business delegate" via a JavaBean.

The Value Object is used to encapsulate the business data. A single method call is used to send and retrieve the Value Object. When the client requests the enterprise bean for the business data, the enterprise bean can construct the Value Object, populate it with its attribute values, and pass it by value to the client.

4. What is the Prototype design pattern? Prototype design pattern is a creational design pattern. This pattern helps the Object oriented design more flexible elegant and reusable.

5. Explain the concept of Entity Beans and Session Beans. What are the benefits of using an Application Server? Is it possible that in certain situations you would not use an AppServer? Why?

The Enterprise JavaBeans architecture is a component architecture for the development and deployment of component-based distributed business applications. Applications written using the Enterprise JavaBeans architecture are scalable, transactional, and multi-user secure. These applications may be written once, and then deployed on any server platform that supports the Enterprise JavaBeans specification. A session bean is a type of enterprise bean; a type of EJB server-side component. Session bean components implement the javax.ejb.SessionBean interface and can be stateless or stateful. Stateless session beans are components that perform transient services; stateful session beans are components that are dedicated to one client and act as a server-side extension of that client. Session beans can act as agents modeling workflow or provide access to special transient business services. As an agent, a stateful session bean might represent a customer's session at an online shopping site. As a transitive service, a stateless session bean might provide access to validate and process credit card orders. Session beans do not normally represent persistent business concepts like Employee or Order. This is the domain of a different component type called an entity bean. An entity bean is a type of enterprise bean; a type of EJB server-side component. Entity bean components implement the javax.ejb.EntityBean interface and can be container-managed (CMP) or bean-managed (BMP). Entity beans are designed to represent data in the database; they wrapper data with business object semantics and read and update data automatically. Entity beans can be safely shared by many clients, so that several applications can access the same bean identity at the concurrently

Web Server & Application Server:


Yes, it is possible to use the Web server alone in certain circumstances such as, if you are hosting a website serving static HTML pages.

The Web server, in general, sends Web pages to browsers as its primary function. Most Web servers also process input from users, format data, provide security, and

perform other tasks. The majority of a Web server�s work is to execute HTML or scripting such as Perl, JavaScript, or VBScript

An application server prepares material for the Web server -- for example, gathering data from databases, applying business rules, processing security clearances, or storing the state of a user�s session. In some respects the term application server is misleading since the functionality isn�t limited to applications. Its role is more as an aggregator and manager for data and processes used by anything running on a Web server. One of the most frequent causes of poor Web server performance is data management or data-related transactions. Web servers and HTML in particular were not designed for large-scale data handling. Application servers shine at managing data. XML translation, communication with database servers, validating data, and applying business rules are all functions for which application servers were originally designed. A key element may be the business rules.

6. Explain final, finalize, and finally. When the finalize is invoked? How does GC work? etc.

Keyword final is equivalent to const in c/c++. If you declare a variable as final in Java the value will be unaltered. That variable will not be created per instance basis.

Finally is tied with exception handling try catch. Finally block will be executed, even if the exception is caught or NOT. Usually used for closing open connections files etc.

The garbage collector invokes an object's finalize() method when it detects that the object has become unreachable. 7. In a system that you are designing and developing, a lot of small changes are expected to be committed at the end of a method call (persisted to the DB). If you don't want to query the database frequently. what would you do? 8. What is a two-phase commit? Two phase commit technology has been used to automatically control and monitor commit and/or rollback activities for transactions in a distributed database system. Two phase commit technology is used when data updates need to occur simultaneously at multiple databases within a distributed system. Two phase commits are done to maintain data integrity and accuracy within the distributed databases through synchronized locking of all pieces of a transaction. Two phase commit is a proven solution when data integrity in a distributed system is a requirement. Two phase commit technology is used for hotel and airline reservations, stock market transactions, banking applications, and credit card systems

9.Give an algorithm that calculates the distance between two text strings (only operations you can have are: delete, add, and change, one by one). Given the definition of a sequence (5 4 7 6 is, but 1 2 4 5 is not), write an algorithm to check if an arbitrary array is a sequence or not. 10.Describe a situation where concurrent access would lead to inconsistency in your application. How would you solve this problem? Make the respective class synchronized. 11.What is the difference between RMI and IIOP? The Remote Method Invocation classes in JDK 1.1 provide a simple, yet extremely powerful, distributed object model for Java. Although RMI is language-specific, because of Java's platform-neutrality, RMI can be utilised widely, and with the use of JDBC can provide basic object-relational mapping capabilities or with JNI, can provide access to platform-specific capabilities. The IIOP (Internet Inter-ORB Protocol) protocol connects CORBA products from different vendors, ensuring interoperability among them. RMI-IIOP is, in a sense, a marriage of RMI and CORBA. 12.Draw a class diagram (UML) for a system. 13.Which do you prefer, inheritance or delegation? Why? Please refer http://www.objectmentor.com/resources/listArticles? key=date&date=2002 14.What is the difference between the JDK 1.02 event model and the eventdelegation model introduced with JDK 1.1?

The JDK 1.02 event model uses an event inheritance or bubbling approach. In this model, components are required to handle their own events. If they do not handle a particular event, the event is inherited by (or bubbled up to) the component's container. The container then either handles the event or it is bubbled up to its container and so on, until the highest-level container has been tried. In the event-delegation model, specific objects are designated as event handlers for GUI components. These objects implement event-listener interfaces. The eventdelegation model is more efficient than the event-inheritance model because it eliminates the processing required to support the bubbling of unhandled events.

15. Give an example of using JDBC access the database.

try { Class.forName("register the driver"); Connection con = DriverManager.getConnection("url of db", "username","password"); Statement state = con.createStatement(); state.executeUpdate("create table testing(firstname varchar(20), lastname varchar(20))");

state.executeQuery("insert into testing values('phu','huynh')"); con.commit(); } catch(Exception e) { System.out.println(e); }finally { state.close(); con.close(); }

16. Difference of RequestDispatcher and sendRedirect ?

getRequestDispatcher is a method of ServletContext 1. forward is handled completely on the server 2.preserve all the request data, request state on the server 3.the URL of the original servlet is maintained 4.does not require a round trip to the client, and thus more efficient sendRedirect is a method of HttpServletResponse 1.requires the client to reconnect to the new resource, the request is first sent to the client which requests for the resource mentioned in the argument of sendRedirect method. 2.does not automatically preserve all the request data result in a different final URL (convert relative URL to absolute URL) 17.Can you tell me what iterators and enumerators are? In any collection class, you must have a way to put things in and a way to get things out. Enumerations and iterators are used to get the object out from a collection class. One benefit of using iterators over enumerations is iterators check for concurrent modifications when you access each element. Enumerators faster than Iterators. 18.You know what a queue is .... Implement a queue class with Java. What is the cost of enqueue and dequeue? Can you improve this? What if the queue is full? What kind of mechanism would you use to increase its size? Please refer : Queue.doc

19. Difference between String & StringBuffer? String object is immutable that is string is constant. StringBuffer StringBufffer will give better performance than String object. 20 What is synchronization and why is it important? With respect to multithreading, synchronization is the capability to is mutable.

control the access of multiple threads to shared resources. Without synchronization, it is is in the possible for one thread to modify a shared object while another thread

process of using or updating that object's value. This often leads to significant errors.

21 What's the diffence between green threads and native threads?

Green threads are the default threads provided by the JDKTM. Native threads are the threads that are provided by the native OS: Native threads can provide several advantages over the default green threads implementation, depending on your computing situation. Benefits of using the native threads: If you run JavaTM code in a multi-processor environment, the Solaris kernel can schedule native threads on the parallel processors for increased performance. By contrast, green threads exist only at the user-level and are not mapped to multiple kernel threads by the operating system. Performance enhancement from parallelism cannot be realized using green threads. The native threads implementation can call into C libraries that use Solaris native threads. Such libraries cannot be used with green threads.

When using the native threads, the VM can avoid some inefficient remapping of I/O system calls that are necessary when green threads are used.

22 How do you run OS commands from JAVA Using Runtime.getRuntime.execute() command)

23 Does a varibale displayed in XSL can it be changed Ans: NO

24 Diff between SAX and DOM XML Parsers, DOM is more powerful reads the complete and parse, SAX parse segment

by segment sequentially

25 Can the SingleTon Pattern will work in multiple JVM's Not Sure, my answer is: NO

27 Thread Isolation levels 28 How do you delete Duplicate rows in Oracle DB Deleting Duplicate Rows when there is a Primary key: DELETE FROM Customers WHERE ID IN (SELECT ID FROM (SELECT ID, LastName, FirstName, RANK() OVER (PARTITION BY LastName, FirstName ORDER BY ID) AS SeqNumber FROM (SELECT ID, LastName, FirstName FROM Customers WHERE (LastName, FirstName) IN (SELECT LastName, FirstName FROM Customers GROUP BY LastName, FirstName HAVING COUNT(*) > 1))) WHERE SeqNumber > 1);

Deleting Duplicate Rows when there no Primary Key: This technique works for tables that have no primary key�which, by itself,

is a sign of bad database design, but that's another topic for discussion. For such tables, you can use the ROWID pseudocolumn instead of the primary key to get the same result:

DELETE FROM Customers WHERE ROWID IN (SELECT MyKey FROM (SELECT MyKey, LastName, FirstName, SeqNumber RANK() OVER (PARTITION BY LastName, FirstName ORDER BY MyKey) AS FROM (SELECT ROWID AS MyKey, LastName, FirstName FROM Customers WHERE (LastName, FirstName) IN (SELECT LastName, FirstName FROM Customers GROUP BY LastName, FirstName HAVING COUNT(*) > 1))) WHERE SeqNumber > 1);

29 What is SAAJ?

SOAP with Attachment API for JAVA

30 How do you make Servlet Thread Safe? By extending the Servelt from SingleThread

31 What are Models in Assets a) Small Mid Specialty Taxable, Growth Specialty Taxable b) Foreign Equity Specialty Taxable, c) Conservative Tax Deferred, Conservative Taxable d) Income and Growth Tax Deferred, Income and Growth Taxable e) Moderate Growth Tax Deferred, Moderate Growth Taxable f) Growth Tax Deferred, Growth Taxable, Aggressive Growth Tax Deferred

32 What is the Life Cycle of a Servelt? Instantiate->Init--> Service --> destroy

33 How do you make a class SingleTon.

By making the class Final and writing constructor Private

34. JSP page life Cycle:

There are 7 phases in the JSP life cycle: 1 : Page Translation : The page is parsed and the java file containing the servlet is created. 2 : Page Compilation : The java file is compiled. 3 : Load Class : The compiled class is Loaded. 4 : Create Instance : An instance of the servlet is created. 5 : call_JSPInit( ) : This method is called before any other method to allow initialization. 6 : call_JSPService() : This method is called for each request 7 : call_JSPDestroy() : This method is called when the servlet container decides to take the servlet out of service

35 What is Serialization and externalization Serialization: Converting Byte to Stream Externalization : Stream to Byte

36. Diff between ArrayList and Vector

ArrayList is not synchronized but Vector is. ArrayList is faster than Vector. Vector has many legacy methods.

37. HashMap, HashTable and TreeMap.

HashMap is unsynchronized and permits nulls. This class makes no guarantees as to the order of the map; in particular, it does not guarantee that the order will remain constant over time. HashMap is not Synchronized so it is good in performance. HashTable is Synchronised.

The point of a TreeMap is that you get the results in sorted order. TreeMap is the only Map with the subMap( ) method, which allows you to return a portion of the tree. The TreeMap is generally slower than the HashMap

38. Diff between int and Integer

int: primitive data type. Integer: Object, Wrapper class of int.

39.Diff between Static and Final? A static method is a method that's invoked through a class, rather than a specific object of that class A final method is just a method that cannot be overridden Static methods can be overriden, but they cannot be overriden to be non-static, Whereas final methods cannot be overriden.

40. How to prevent a variable from Serialization?

To prevent serialization declare the variable as "Transient".

41. What are UserDefined Exceptions?

User Defined exception are the programmer created software detected exceptions. Programs may name their own exceptions by assigning a string to a variable or creating a new exception class is called User defined exception

42. Explain about Garbage Collector?

The name "garbage collection" implies that objects that are no longer needed by the program are "garbage" and can be thrown away. A more accurate and up-to-date metaphor might be "memory recycling." When an object is no longer referenced by the program, the heap space it occupies must be recycled so that the space is available for subsequent new objects. The garbage collector must somehow determine which objects are no longer referenced by the program and make available the heap space occupied by such unreferenced objects. In the process of freeing unreferenced objects, the garbage collector must run any finalizers of objects being freed.

Advantages: First, it can make programmers more productive

A second advantage of garbage collection is that it helps ensure program integrity. Garbage collection is an important part of Java's security strategy. Java programmers are unable to accidentally (or purposely) crash the JVM by incorrectly freeing memory.

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

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

45. What is synchronization and why is it important?

control the

With respect to multithreading, synchronization is the capability to

access of multiple threads to shared resources. Without synchronization, it is is in the possible for one thread to modify a shared object while another thread

process of using or updating that object's value. This often leads to significant errors.

46. What is the difference between yielding and sleeping?

When a task invokes its yield() method, it returns to the ready state. When a task invokes its sleep() method, it returns to the waiting state.

47. Does garbage collection guarantee that a program will not run out of memory?

of memory. they

Garbage collection does not guarantee that a program will not run out It is possible for programs to use up memory resources faster than

are garbage collected. It is also possible for programs to create objects that are not subject to garbage collection

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

49 When a thread is created and started, what is its initial state?

A thread is in the ready state after it has been created and started.

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

51. What invokes a thread's run() method?

After a thread is started, via its start() method or that of the Thread class, executed. the JVM invokes the thread's run() method when the thread is initially

52. What is the purpose of the Runtime class?

The purpose of the Runtime class is to provide access to the Java runtime system and to use the Operating System commands.

53. What is the relationship between the Canvas class and the Graphics class?


A Canvas object provides access to a Graphics object via its paint()

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

55. What is the Dictionary class?

The Dictionary class provides the capability to store key-value pairs.

56 Name the eight primitive Java types.

The eight primitive types are byte, char, short, int, long, float, double, and boolean.

57 What is the relationship between an event-listener interface and an eventadapter class?

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

58. What modifiers can be used with a local inner class?

A local inner class may be final or abstract.

59. Diff between Overloading and OverRiding?

Overloading : Same name, different Signature Overriding : same name, same signature

Employee Class difines public void giveRaise( double percentage)

Boss class can Override giveRaise

public void giveRaise(double percentage){ -----}

Boss can Overload giveRaise

public void giveRaise(String newTitle){ ---}

Overloaded method called depends on arguments.

Restrictions of Method Overriding: Overridden overriding overriding overridden methods must have the same name, argument list, and return type. The method may not limit the access of the method it overrides. The method may not throw any exceptions that may not be thrown by the method.

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

61 What is Stack and Heap ? If you declare a primitive type such as declaring a variable where does it store? Where does JVM referes all the live Objects?

The Java stack is used to store parameters for and results of bytecode instructions, to pass parameters to and return values from methods, and to keep the state of each method invocation. The state of a method invocation is called its stack frame. The vars, frame, and optop registers point to different parts of the current stack frame. The heap is where the objects of a Java program live. Any time you allocate memory with the new operator, that memory comes from the heap. The Java language doesn't allow you to free allocated memory directly. Instead, the runtime environment keeps track of the references to each object on the heap, and automatically frees the memory occupied by objects that are no longer referenced -- a process called garbage collection.

62 Explain the doStartTag() and doEndTag() methods ?

The doStartTag() and doEndTag() methods belong to the Tag interface of the javax.servlet.jsp.tagext package. The Tag interface provides methods that connect a tag handler (a tag handler is an object invoked by a web container/server to evaluate a custom tag during the execution of the JSP page that references the tag.) with a JSP implementation class , including the life cycle methods and methods that are invoked at the start and end tag. The method doStartTag() processes the start tag associated with a JSP while the doEndTag() method processes the end tag associated with a JSP.

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

64 Explain how do you implement Tags

in JSP ?

The "taglib" directive is included in a JSP page which uses tags defined a tag library. Here is the syntax for that:

<%@ taglib uri="URI" prefix="prefix" %>

The uri refers to a URI (Uniform Resource Identifier, a term referring to any specification that identifies an object on the internet) that uniquely identifies the TLD, tag library descriptor. A tag library descriptor is an XML document that

describes a tag library. The prefix attribute defines the prefix that distinguishes tags defined by a given tag library from those provided by other tag libraries.

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

66 For a CMP Bean what should the EjbCreate returns? Remote Interface

67 What is the order of method invocation in an Applet ?

68 How will you pass values from HTML page to the Servlet ? session or cookies

69 How does thread synchronization occurs inside a monitor?

70 Can you load the server object dynamically? If so, what are the major 3 steps involved in it ?

71 What is difference in between Java Class and Bean ? A Java Bean is a java class object that encapsulates data in the form of instance variables. These variables are reffered to as properties of the bean. The class then provides a set of methods for accessing and mutating its properties.

72. You add web components to a J2EE application in a package called WAR (web application archive). A WAR has a specific hierarchical directory structure. Which directory stores the deployment descriptor for a Web application located in the myapp directory?

An application located in the myapp directory will have its deployment descriptor in the myapp/WEB-INF directory.

73 Suppose If we have variable ' I ' in run method, If I can create one or more thread each thread will occupy a separate copy or same variable will be shared ?

74 What are session variable in Servlets? 75 What are the Normalization Rules ? Define the Normalization ? First Normal Form For a table to be in First Normal Form (1NF) each row must be identified, all columns in the table must contain atomic values, and each field must be unique.

Second Normal Form For a table to be in Second Normal Form (2NF), it must be already in 1NF and it contains no partial key functional dependencies. In other words, a table is said to be in 2NF if it is a 1NF table where all of its columns that are not part of the key are dependent upon the whole key - not just part of it.

Third Normal Form A table is considered to be in Third Normal Form (3NF) if it is already in Second Normal Form and all columns that are not part of the primary key are dependent entirely on the primary key. In other words, every column in the table must be dependent upon "the key, the whole key and nothing but the key."

76 What is meant by class loader? How many types are there? When will we use them? The class ClassLoader is an abstract class. A class loader is an object that is responsible for loading classes. Given the name of a class, it should attempt to locate or generate data that constitutes a definition for the class. A typical strategy is to transform the name into a file name and then read a "class file" of that name from a file system. Applications implement subclasses of ClassLoader in order to extend the manner in which the Java virtual machine dynamically loads classes. The ClassLoader class uses a delegation model to search for classes and resources

77 How do you load an Image in a Servlet ? 78 What is meant by cookies ? Explain ? Cookies are a general mechanism which server side connections

can use to both

store and retrieve information on the client side of the connection. A cookie is a unique identifier that a web server places on your computer: a serial number for you personally that can be used to retrieve your records from their databases. It's usually a string of random-looking letters long enough to be unique. They are kept in a file called cookies or cookies.txt or MagicCookie in your browser directory/folder. They are also known as ``persistent cookies'' because they may last for years, even if you change ISP or upgrade your browser.

79 Wrapper class. Is String a Wrapper Class Example : Integer is a wrapper class of int. String is not a wrapper class.

80 Checked & Unchecked exception � Use checked exceptions for conditions that client code may reasonably be expected to handle. This compile-time checking for the presence of exception handlers is designed to reduce the number of exceptions which are not properly handled." � If you are throwing an exception for an abnormal condition that you feel client programmers should consciously decide how to handle, throw a checked exception. � Unchecked exceptions indicate software bugs.

� Precisely because unchecked exceptions usually represent software bugs, they often can't be handled somewhere with more context. 81 Explain lazy activation Lazy activation defers activating an object until a client's first use (i.e., the first method invocation). Delay activation until the first client request for the object. Uses faulting remote references The faulting remote reference contains a persistent activation handle (reference) for the remote object and a transient remote reference to the remote object. The transient remote reference can be null. On the first reference to the remote object, if the transient remote reference is null, the persistent activation handle is used to contact (directly or indirectly) the activator for the remote object. If need be the activator activates the object and returns the proper remote reference to the remote object.

82 How do you delete a HttpSession.

The invalidate() method of the HttpSession interface expires the current session. It causes the representation of the session to be invalidated and removed from its context. 83 What is the different of an Applet and a Java Application

In simple terms, an applet runs under the control of a browser, whereas an

application runs stand-alone, with the support of a virtual machine. As such, an applet is subjected to more stringent security restrictions in terms of file and network access, whereas an application can have free reign over these resources.

Applets are great for creating dynamic and interactive web applications, but the true power of Java lies in writing full blown applications. With the limitation of disk and network access, it would be difficult to write commercial applications (though through the user of server based file systems, not impossible). However, a Java application has full network and local file system access, and its potential is limited only by the creativity of its developers. 84. How do we pass a reference parameter to a function in Java?

Even though Java doesn't accept reference parameter, but we can pass in the object for the parameter of the function. For example in C++, we can do this: void changeValue(int& a) { a++; } void main() { int b=2; changeValue(b); } however in Java, we cannot do the same thing. So we can pass the the int value into Integer object, and we pass this object into the the function. And this function will change the object. 85. Explain the difference between the equals() method, and the == operator - what happens if .equals() is not defined? (bit wise comparison) - we had a bit of an argument about stringss being given the same address by the compile 86. How do you put an object on the stack in java? Stack is inherited from Vector. So it has all of the characteristics and behaviors of a Vector plus some extra Stack behaviors. Stack stk = new Stack(); for(int i = 0; i < months.length; i++) stk.push(months[i] + " "); System.out.println("stk = " + stk); // Treating a stack as a Vector: stk.addElement("The last line"); 87 What can't you do in an EJB? You can't use java.io

88. Do you know about text formatter?

89. How would you create a Hashmap from an Array? 90. How would you create a List from an Array?

91. How do you stop a thread?

92. What can you tell me about the reflection package?

The Java Core Reflection API provides a small, type-safe, and secure API that supports introspection about the classes and objects in the current Java Virtual Machine*. If permitted by security policy, the API can be used to:

construct new class instances and new arrays access and modify fields of objects and classes invoke methods on objects and classes access and modify elements of arrays Pls refer to : http://java.sun.com/j2se/1.3/docs/guide/reflection/spec/java-reflection.doc.html

93. Are private member variables saved if class is serializable?

94. A question about the Clonable interface, deep/shallow copies, clone() method

96. What are thread priorities? Thread Priorities (MIN_PRIORITY ( 1 ), NORM_PRIORITY ( 5 ) , MX_PRIORITY ( 10 ) )

97 What is difference in between Java Class and Bean ? What differentiates Beans from typical Java classes is introspection. Tools that recognize predefined patterns in method signatures and class definitions can "look inside" a Bean to determine its properties and behavior. A Bean's state can be manipulated at the time it is being assembled as a part within a larger application. The application assembly is referred to as design time in contrast to

run time. In order for this scheme to work, method signatures within Beans must follow a certain pattern in order for introspection tools to recognize how Beans can be manipulated, both at design time, and run time. In effect, Beans publish their attributes and behaviors through special method signature patterns that are recognized by beans-aware application construction tools. However, you need not have one of these construction tools in order to build or test your beans. The pattern signatures are designed to be easily recognized by human readers as well as builder tools. One of the first things you'll learn when building beans is how to recognize and construct methods that adhere to these patterns. 98.Why might you define a method as native? Native methods are methods implemented in another programming language such as C/C++. To get to access hardware that Java does not know about To write optimized code for performance in a language such as C/C++ 99. Which design patterns reduces the coupling between presentation-tier clients and business services in a web application? Business Delegate In a normal scenario, presentation-tier components (e.g. a JSP) interact directly with business services. As a result, the presentation-tier components are vulnerable to changes in the implementation of the business services: when the implementation of the business services change, the code in the presentation tier must change. The goal of Business Delegate object design pattern is to minimize the coupling between presentation-tier clients and the business service API, thus hiding the underlying implementation details of the service. In this way we enhance the manageability of the application. Using this design pattern, the client request is first handled by a Servlet that dispatches to a JSP page for formatting and display. The JSP is responsible for delegating the processing of business functionality to a "business delegate" via a JavaBean.

100. Explain the Significance of using the following Design Patterns MVC, DAO(Data Access Object, Value Object)

MVC design pattern provide Multiple View using the same model.

DAO (Data Access Object), which enables easier migration to different persistence storage implementation.

The Value Object is used to encapsulate the business data. A single method call is used to send and retrieve the Value Object. When the client requests the enterprise bean for the business data, the enterprise bean can construct the Value Object, populate it with its attribute values, and pass it by value to the client.

101 Why do you make setAutoCommit(false) for a transaction? setAutoCommit public abstract void setAutoCommit(boolean autoCommit) throws SQLException If a connection is in auto-commit mode, then all its SQL statements will be executed and committed as individual transactions. Otherwise, its SQL statements are grouped into transactions that are terminated by either commit() or rollback(). By default, new connections are in auto-commit mode. The commit occurs when the statement completes or the next execute occurs, whichever comes first. In the case of statements returning a ResultSet, the statement completes when the last row of the ResultSet has been retrieved or the ResultSet has been closed. In advanced cases, a single statement may return multiple results as well as output parameter values. Here the commit occurs when all results and output param values have been retrieved. http://stein.cshl.org/jade/distrib/docs/java.sql.Connection.html#setAutoCommit(boo lean)

102 Explain the soap Request Paradigm

103. Explain the following JAR files and its purpose? Crimson.jar - Crimson is a Java XML parser which supporrts XML 1.0 via the following APIs: EspressAPI - EspressChart provides an easy-to-use application programming interface (API) that enables users to create and customize 2D and 3D charts within their own applications (and applets). It is written in 100% Pure Java, but can use native libraries for a performance boost when exporting. http://www.quadbase.com/espresschart/help/manual/Chp_8.html imap - IMAP is the Internet Message Access Protocol, or as it was once known, the Interactive Mail Access Protocol. It represents a communications mechanism for mail clients to interact with mail servers, and manipulate mailboxes thereon. Perhaps the most popular mail access protocol currently is the Post Office Protocol (POP), which also addresses remote mail access needs. IMAP offers a superset of POP features, which allow much more complex interactions and provides for much more efficient access than the POP model. IText � Used to convert a rtf file to a PDF file http://www.lowagie.com/iText/

THE END Hope this would be a great help for new and experienced java programmers who are attending interviews. I could not include the answers for some of the questions please bear with me. I will update the answers in the future releases� Binoy M.

George Please email your valuable comments and suggestions to: binoymg@hotmail.com

Master your semester with Scribd & The New York Times

Special offer for students: Only $4.99/month.

Master your semester with Scribd & The New York Times

Cancel anytime.