Servlets–>Notes

October 11th, 2006

javax.servlet.Servlet interface is very important because it encapsulates the life cycle methods of a servlet and it is the interface that all servlets must implement. “The javax.servlet Package Reference.”
The seven interfaces are as follows:
• RequestDispatcher
• Servlet
• ServletConfig
• ServletContext
• ServletRequest
• ServletResponse
• SingleThreadModel
The three classes are as follows:
• GenericServlet
• ServletInputStream
• ServletOutputStream
And, finally, the exception classes are these:
• ServletException
• UnavailableException

A Servlet’s Life Cycle
The init( ) Method
The init method is called by the servlet container after the servlet class has been instantiated. The servlet container calls this method exactly once to indicate to the servlet that the servlet is being placed into service. The init method must complete successfully before the servlet can receive any requests. You can override this method to write initialization code that needs to run only once, such as loading a database driver, initializing values
public void init(ServletConfig config) throws ServletException
The service( ) Method
Servlets typically run inside multithreaded servlet containers that can handle multiple requests concurrently. Therefore, you must be aware to synchronize access to any shared resources, such as files, network connections, and the servlet’s class and instance variables.
public void service(ServletRequest request, ServletResponse response)
  throws ServletException, java.io.IOException
The destroy( ) Method
The servlet container calls the destroy method before removing a servlet instance from service. This normally happens when the servlet container is shut down or the servlet container needs some free memory.
This method is called only after all threads within the servlet’s service method have exited or after a timeout period has passed. After the servlet container calls this method, it will not call the service method again on this servlet.
The destroy method gives the servlet an opportunity to clean up any resources that are being held (for example, memory, file handles, and threads) and make sure that any persistent state is synchronized with the servlet’s current state in memory.
The signature of this method is as follows:
public void destroy()
servlet’s config you have the option of specifying a set of initial parameter name/value pairs that you can retrieve from inside the servlet
The getInitParameterNames does not take an argument and returns an Enumeration containing all the parameter names in the ServletConfig object.
 getInitParameter takes a String containing the parameter name and returns a String containing the value of the parameter.

Preserving the ServletConfig :you may want to have access to the ServletConfig object from the service method, when you are servicing the user. In this case, you need to preserve the ServletConfig object to a class level variable.
ServletConfig servletConfig;

servlet’s context, the servlet context is the environment where the servlet runs. The servlet container creates a ServletContext object that you can use to access information about the servlet’s environment.

How do you obtain the ServletContext object? Indirectly, from the ServletConfig object passed by the servlet container to the servlet’s init method. The ServletConfig interface has a method called getServletContext that returns the ServletContext object.

• getAttributeNames. This method returns an enumeration of strings representing the names of the attributes currently stored in the ServletContext.
• getAttribute. This method accepts a String containing the attribute name and returns the object bound to that name.
• setAttribute. This method stores an object in the ServletContext and binds the object to the given name. If the name already exists in the ServletContext, the old bound object will be replaced by the object passed to this method.
• removeAttribute. This method removes from the ServletContext the object bound to a name. The removeAttribute method accepts one argument: the name of the attribute to be removed.
The ServletRequest Interface
The ServletRequest interface defines an object used to encapsulate information about the user’s request, including parameter name/value pairs, attributes, and an input stream.
The ServletResponse Interface
The ServletResponse interface represents the response to the user. The most important method of this interface is getWriter, from which you can obtain a java.io.PrintWriter object that you can use to write HTML tags and other text to the user.

 
The HttpServlet Class
As mentioned previously, the HttpServlet class extends the javax.servlet.GenericServlet class. The HttpServlet class also adds a number of interesting methods for you to use. The most important are the six doxxx methods that get called when a related HTTP request method is used. The six methods are doPost, doPut, doGet, doDelete, doOptions and doTrace. Each doxxx method is invoked when a corresponding HTTP method is used. For instance, the doGet method is invoked when the servlet receives an HTTP request that was sent using the GET method.
setHeader method. This method allows you to add a name/value field to the response header.

sendRedirect method to redirect the user to another page:. When you call this method, the web server sends a special message to the browser to request another page. Therefore, there is always a round trip to the client side before the other page is fetched.
display a special character, you need to encode it. The less-than character (< ) is encoded as "<" and the greater-than character (>) as “>”. Other special characters are the ampersand (&) and double quotation mark (”) characters. You replace the ampersand (&) with “&” and the double quotation marks (”) with “"”. Additionally, two or more white spaces are always displayed as a single space, unless you convert each individual space to “ ”.

Buffering the Response
If response buffering is enabled, the output to the browser is not sent until the servlet processing is finished or the buffer is full. Buffering enhances the performance of your servlet because the servlet needs to send the string output only once, instead of sending it every time the print or println method of the PrintWriter object is called. By default, buffering is enabled and the buffer size is 8,192 characters. You can change this value by using the HttpServletResponse interface’s setBufferSize method. This method can be called only before any output is sent

Populating HTML Elements
two rules:
1. Always enclose a value with double quotation marks (”). This way, white spaces will be rendered correctly.
2. If the value contains a double quotation mark character, you need to encode the double quotation marks (”).

Request Dispatching
In some circumstances, you may want to include the content from an HTML page or the output from another servlet. Additionally, there are cases that require that you pass the processing of an HTTP request from your servlet to another servlet. The current servlet specification responds to these needs with an interface called RequestDispatcher, which is found in the javax.servlet package. This interface has two methods, which allow you to delegate the request-response processing to another resource: include and forward. Both methods accept a javax.servlet.ServletRequest object and a javax.servlet.ServletResponse object as arguments.

As the name implies, the include method is used to include content from another resource, such as another servlet, a JSP page, or an HTML page. The method has the following signature:
public void include(javax.servlet.ServletRequest request,
  javax.servlet.ServletResponse response)
  throws javax.servlet.ServletException, java.io.IOException
The forward method is used to forward a request from one servlet to another. The original servlet can perform some initial tasks on the ServletRequest object before forwarding it. The signature of the forward method is as follows:
public void forward(javax.servlet.ServletRequest request,
  javax.servlet.ServletResponse response)
  throws javax.servlet.ServletException, java.io.IOException

 

The Difference Between sendRedirect and forward
Both the sendRedirect and forward methods bring the user to a new resource. There is a fundamental difference between the two, however, and understanding this can help you write a more efficient servlet.
The sendRedirect method works by sending a status code that tells the browser to request another URL. This means that there is always a round trip to the client side. Additionally, the previous HttpServletRequest object is lost. To pass information between the original servlet and the next request, you normally pass the information as a query string appended to the destination URL.
The forward method, on the other hand, redirects the request without the help from the client’s browser. Both the HttpServletRequest object and the HttpServletResponse object also are passed to the new resource.

To perform a servlet include or forward, you first need to obtain a RequestDispatcher object. You can obtain a RequestDispatcher object three different ways, as follows:
• Use the getRequestDispatcher method of the javax.servlet.ServletContext interface, passing a String containing the path to the other resource. The path is relative to the root of the ServletContext.
• Use the getRequestDispatcher method of the javax.servlet.ServletRequest interface, passing a String containing the path to the other resource. The path is relative to the current HTTP request.
• Use the getNamedDispatcher method of the javax.servlet.ServletContext interface, passing a String containing the name of the other resource.
The include method of the RequestDispatcher interface may be called at any time. The target servlet has access to all aspects of the request object, but can only write information to the ServletOutputStream or Writer object of the response object. The target servlet also can commit a response by either writing content past the end of the response buffer or explicitly calling the flush method of the ServletResponse interface. The included servlet cannot set headers or call any method that affects the header of the response.
When a servlet is being called from within an include method, it is sometimes necessary for that servlet to know the path by which it was invoked. The following request attributes are set and accessible from the included servlet via the getAttribute method on the request object:
• javax.servlet.include.request_uri
• javax.servlet.include.context_path
• javax.servlet.include.servlet_path
• javax.servlet.include.path_info
• javax.servlet.include.query_string
These attributes are not set if the included servlet was obtained by using the getNamedDispatcher method

Forwarding Processing Control
Unlike the include method, the forward method of the RequestDispatcher interface may be called only by the calling servlet if no output has been committed to the client. If output exists in the response buffer that has not been committed, the buffer must be cleared before the target servlet’s service method is called. If the response has been committed prior to calling the forward method, an IllegalStateException will be thrown.

 

Session Management
Once users have logged in, they do not have to login again. The application will remember them. This is called session management.Needed because of HTTP statelessness.

By principle, you manage a user’s session by performing the following to servlets/pages that need to remember a user’s state:
1. When the user requests a servlet, in addition to sending the response, the servlet also sends a token or an identifier.
2. If the user does not come back with the next request for the same or a different servlet, that is fine. If the user does come back, the token or identifier is sent back to the server. Upon encountering the token, the next servlet should recognize the identifier and can do a certain action based on the token. When the servlet responds to the request, it also sends the same or a different token. This goes on and on with all the servlets that need to remember a user’s session.
Methods
URL Rewriting
A name and a value is separated using an equal sign (=); a parameter name/value pair is separated from another parameter name/value pair using the ampersand (&). When the user clicks the hyperlink, the parameter name/value pairs will be passed to the server. From a servlet, you can use the HttpServletRequest interface’s getParameter method to obtain a parameter value.
url?name1=value1&name2=value2&…
The use of URL rewriting is easy. When using this technique, however, you need to consider several things:
• The number of characters that can be passed in a URL is limited. Typically, a browser can pass up to 2,000 characters.
• The value that you pass can be seen in the URL. Sometimes this is not desirable. For example, some people prefer their password not to appear on the URL.
• You need to encode certain characters—such as & and ? characters and white spaces—that you append to a URL.
Hidden Fields
Another technique for managing user sessions is by passing a token as the value for an HTML hidden field. Unlike the URL rewriting, the value does not show on the URL but can still be read by viewing the HTML source code.

Cookies
The third technique that you can use to manage user sessions is by using cookies. A cookie is a small piece of information that is passed back and forth in the HTTP request and response. Even though a cookie can be created on the client side using some scripting language such as JavaScript, it is usually created by a server resource, such as a servlet. The cookie sent by a servlet to the client will be passed back to the server when the client requests another page from the same application. You can choose to persist cookies so that they last longer. The javax.servlet.http.Cookie class has the setMaxAge method that sets the maximum age of the cookie in seconds.

Session Objects
the Session object, represented by the javax.servlet.http.HttpSession interface, is the easiest to use and the most powerful. For each user, the servlet can create an HttpSession object that is associated with that user only and can only be accessed by that particular user. The HttpSession object acts like a Hashtable into which you can store any number of key/object pairs. The HttpSession object is accessible from other servlets in the same application. To retrieve an object previously stored, you need only to pass the key. however, the server does not send any value. What it sends is simply a unique number called the session identifier. This session identifier is used to associate a user with a Session object in the server
1. An HttpSession object is created by a servlet called Servlet1. A session identifier is generated for this HttpSession object. In this example, the session identifier is 1234, but in reality, the servlet container will generate a longer random number that is guaranteed to be unique. The HttpSession object then is stored in the server and is associated with the generated session identifier. Also the programmer can store values immediately after creating an HttpSession.
2. In the response, the servlet sends the session identifier to the client browser.
3. When the client browser requests another resource in the same application, such as Servlet2, the session identifier is sent back to the server and passed to Servlet2 in the javax.servlet.http.HttpServletRequest object.
4. For Servlet2 to have access to the HttpSession object for this particular client, it uses the getSession method of the javax.servlet.http.HttpServletRequest interface. This method automatically retrieves the session identifier from the request and obtains the HttpSession object associated with the session identifier.

What if the user never comes back after an HttpSession object is created? Then the servlet container waits for a certain period of time and removes that HttpSession object.
The getSession method of the javax.servlet.http.HttpServletRequest interface has two overloads. They are as follows:
• HttpSession getSession()
• HttpSession getSession(boolean create)
The first overload returns the current session associated with this request, or if the request does not have a session identifier, it creates a new one.
The second overload returns the HttpSession object associated with this request if there is a valid session identifier in the request. If no valid session identifier is found in the request, whether a new HttpSession object is created depends on the create value. If the value is true, a new HttpSession object is created if no valid session identifier is found in the request. Otherwise, the getSession method will return null.

The javax.servlet.http.HttpSession Interface
This interface has the following methods:
• getAttribute
• getAttributeNames
• getCreationTime
• getId
• getLastAccessedTime
• getMaxInactiveInterval
• getServletContext
• getSessionContext
• getValue
• getValueNames
• invalidate
• isNew
• putValue
• removeAttribute
• removeValue
• setAttribute
• setMaxInactiveInterval

 

 


No Comments »

Core Java Interview Questions

October 11th, 2006

1.what is a transient variable?

A transient variable is a variable that may not be serialized.

2.which containers use a border Layout as their default layout? 

The window, Frame and Dialog classes use a border layout as their default layout.

 

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

 

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

 

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

 

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

 

7. What’s new with the stop(), suspend() and resume() methods in JDK 1.2? 

The stop(), suspend() and resume() methods have been deprecated in JDK 1.2.

 

8. Is null a keyword? 

The null value is not a keyword.

 

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

 

10. What method is used to specify a container’s layout? 

The setLayout() method is used to specify a container’s layout.

 

11. Which containers use a FlowLayout as their default layout? 

The Panel and Applet classes use the FlowLayout as their default layout.

 

12. What state does a thread enter when it terminates its processing? 

When a thread terminates its processing, it enters the dead state.

 

13. What is the Collections API? 

The Collections API is a set of classes and interfaces that support operations on collections of objects.

 

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

 

15. What is the List interface? 

The List interface provides support for ordered collections of objects.

 

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

 

 

17. What is the Vector class? 

The Vector class provides the capability to implement a growable array of objects

 

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

 

19. What is an Iterator interface? 

The Iterator interface is used to step through the elements of a Collection.

 

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

 

21. Which method of the Component class is used to set the position and  

size of a component? 

setBounds()

 

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

 

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

 

24. Which java.util classes and interfaces support event handling? 

The EventObject class and the EventListener interface support event processing.

 

25. Is sizeof a keyword? 

The sizeof operator is not a keyword.

 

26. What are wrapped classes? 

Wrapped classes are classes that allow primitive types to be accessed as objects.

 

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

 

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

 

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

 

30. What is the immediate superclass of the Applet class? 

Panel

 

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

 

32. Name three Component subclasses that support painting. 

The Canvas, Frame, Panel, and Applet classes support painting.

 

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

 

34. What is the immediate superclass of the Dialog class? 

Window

 

35. What is clipping? 

Clipping is the process of confining paint operations to a limited area or shape.

 

36. What is a native method? 

A native method is a method that is implemented in a language other than Java.

 

37. Can a for statement loop indefinitely? 

Yes, a for statement can loop indefinitely. For example, consider the following:

for(;;) ;

 

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

 

39. When a thread blocks on I/O, what state does it enter? 

A thread enters the waiting state when it blocks on I/O.

 

40. To what value is a variable of the String type automatically initialized? 

The default value of an String type is null.

 

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

 

42. What is the difference between a MenuItem and a CheckboxMenuItem? 

The CheckboxMenuItem class extends the MenuItem class to support a menu item that may be checked or unchecked.

 

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

 

44. What class is the top of the AWT event hierarchy? 

The java.awt.AWTEvent class is the highest-level class in the AWT event-class hierarchy.

 

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

 

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

 

47. What is the range of the short type? 

The range of the short type is -(2^15) to 2^15 - 1.

 

48. What is the range of the char type? 

The range of the char type is 0 to 2^16 - 1.

 

 

49. In which package are most of the AWT events that support the event-delegation  

model defined? 

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.

 

50. What is the immediate superclass of Menu? 

MenuItem

 

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

 

52. Which class is the immediate superclass of the MenuComponent class. 

Object

 

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

 

54. What is the difference between the Boolean & operator and the && operator? 

If an expression involving the Boolean & operator is evaluated, both operands are evaluated. Then the & operator is applied to the operand. When an expression involving the && operator is evaluated, the first operand is evaluated. If the first operand returns a value of true then the second operand is evaluated. The && operator is then applied to the first and second operands. If the first operand evaluates to false, the evaluation of the second operand is skipped.

 

55. Name three subclasses of the Component class. 

Box.Filler, Button, Canvas, Checkbox, Choice, Container, Label, List, Scrollbar, or TextComponent

 

56. What is the GregorianCalendar class? 

The GregorianCalendar provides support for traditional Western calendars.

 

57. Which Container method is used to cause a container to be laid out and redisplayed? 

validate()

 

58. What is the purpose of the Runtime class? 

The purpose of the Runtime class is to provide access to the Java runtime system.

 

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

 

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

 

61. What is the argument type of a program’s main() method? 

A program’s main() method takes an argument of the String[] type.

 

62. Which Java operator is right associative? 

The = operator is right associative.

 

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

 

 

64. Can a double value be cast to a byte? 

Yes, a double value can be cast to a byte.

 

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

 

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

 

67. What method is invoked to cause an object to begin executing as a separate thread? 

The start() method of the Thread class is invoked to cause an object to begin executing as a separate thread.

 

68. Name two subclasses of the TextComponent class. 

TextField and TextArea

 

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

 

70. Which containers may have a MenuBar? 

Frame

 

71. How are commas used in the intialization and iterationparts of a for statement? 

Commas are used to separate multiple statements within the initialization and iteration parts of a for statement.

 

 

72. What is the purpose of the wait(), notify(), and notifyAll() methods? 

The wait(),notify(), and notifyAll() methods are used to provide an efficient way for threads to wait for a shared resource. When a thread executes an object’s wait() method, it enters the waiting state. It only enters the ready state after another thread invokes the object’s notify() or notifyAll() methods.

 

73. What is an abstract method? 

An abstract method is a method whose implementation is deferred to a subclass.

 

74. How are Java source code files named? 

A Java source code file takes the name of a public class or interface that is defined within the file. A source code file may contain at most one public class or interface. If a public class or interface is defined within a source code file, then the source code file must take the name of the public class or interface. If no public class or interface is defined

within a source code file, then the file must take on a name that is different than its classes and interfaces. Source code files use the .java extension.

 

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

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

 

76. What are the high-level thread states? 

The high-level thread states are ready, running, waiting, and dead.

 

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

 

 

78. Can a Byte object be cast to a double value? 

No, an object cannot be cast to a primitive value.

 

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

 

80. What is the difference between the String and StringBuffer classes? 

String objects are constants. StringBuffer objects are not.

 

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

 

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

 

83. What is the Dictionary class? 

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

 

84. How are the elements of a BorderLayout organized? 

The elements of a BorderLayout are organized at the borders (North, South, East, and West) and the center of a container.

 

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

 

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

 

87. What is the difference between a Window and a Frame? 

The Frame class extends Window to define a main application window that can have a menu bar.

 

88. Which class is extended by all other classes? 

The Object class is extended by all other classes.

 

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

 

90. Is the ternary operator written x : y ? z or x ? y : z ? 

It is written x ? y : z.

 

91. What is the difference between the Font and FontMetrics classes? 

The FontMetrics class is used to define implementation-specific properties, such as ascent and descent, of a Font object.

 

92. How is rounding performed under integer division? 

The fractional part of the result is truncated. This is known as rounding toward zero.

 

93. What happens when a thread cannot acquire a lock on an object? 

If a thread attempts to execute a synchronized method or synchronized statement and is unable to acquire an object’s lock, it enters the waiting state until the lock becomes available.

 

 

 

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

 

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

 

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

 

97. What is the SimpleTimeZone class? 

The SimpleTimeZone class provides support for a Gregorian calendar.

 

98. What is the Map interface? 

The Map interface replaces the JDK 1.1 Dictionary class and is used associate keys with values.

 

 

99. Does a class inherit the constructors of its superclass? 

A class does not inherit constructors from any of its superclasses.

 

100. For which statements does it make sense to use a label? 

The only statements for which it makes sense to use a label are those statements that can enclose a break or continue statement.

 

101. What is the purpose of the System class? 

The purpose of the System class is to provide access to system resources.

 

102. Which TextComponent method is used to set a TextComponent to the read-only state? 

setEditable()

 

103. How are the elements of a CardLayout organized? 

The elements of a CardLayout are stacked, one on top of the other, like a deck of cards.

 

104. Is &&= a valid Java operator? 

No, it is not.

 

105. Name the eight primitive Java types. 

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

 

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

 

107. What is the relationship between clipping and repainting? 

When a window is repainted by the AWT painting thread, it sets the clipping regions to the area of the window that requires repainting.

 

108. Is “abc” a primitive value? 

The String literal “abc” is not a primitive value. It is a String object.

 

109. What is the relationship between an event-listener interface and an  

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

 

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

 

111. What modifiers may be used with an interface declaration? 

An interface may be declared as public or abstract.

 

112. Is a class a subclass of itself? 

A class is a subclass of itself.

 

113. What is the highest-level event class of the event-delegation model? 

The java.util.EventObject class is the highest-level class in the event-delegation class hierarchy.

 

114. What event results from the clicking of a button? 

The ActionEvent event is generated as the result of the clicking of a button.

 

115. How can a GUI component handle its own events? 

A component can handle its own events by implementing the required event-listener interface and adding itself as its own event listener.

 

116. What is the difference between a while statement and a dostatement? 

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.

 

117. How are the elements of a GridBagLayout organized? 

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.

 

118. What advantage do Java’s layout managers provide over traditional windowing systems? 

Java uses layout managers to lay out components in a consistent manner across all windowing platforms. Since Java’s layout managers aren’t tied to absolute sizing and positioning, they are able to accomodate platform-specific differences among windowing systems.

 

119. What is the Collection interface? 

The Collection interface provides support for the implementation of a mathematical bag - an unordered collection of objects that may contain duplicates.

 

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

A local inner class may be final or abstract.

 

121. What is the difference between static and non-static variables? 

A static variable is associated with the class as a whole rather than with specific instances of a class. Non-static variables take on unique values with each object instance.

 

122. What is the difference between the paint() and repaint() methods? 

The paint() method supports painting via a Graphics object. The repaint() method is used to cause paint() to be invoked by the AWT painting thread.

 

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

 

124. Can an exception be rethrown? 

Yes, an exception can be rethrown.

 

125. Which Math method is used to calculate the absolute value of a number? 

The abs() method is used to calculate absolute values.

 

126. How does multithreading take place on a computer with a single CPU? 

The operating system’s task scheduler allocates execution time to multiple tasks. By quickly switching between executing tasks, it creates the impression that tasks execute sequentially.

 

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

 

128. When is the finally clause of a try-catch-finally statement executed? 

The finally clause of the try-catch-finally statement is always executed unless the thread of execution terminates or an exception occurs within the execution of the finally clause.

 

129. Which class is the immediate superclass of the Container class? 

Component

 

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

 

131. How can the Checkbox class be used to create a radio button? 

By associating Checkbox objects with a CheckboxGroup.

 

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

 

133. What restrictions are placed on method overloading? 

Two methods may not have the same name and argument list but different return types.

 

134. What happens when you invoke a thread’s interrupt method while it is  

sleeping or waiting? 

When a task’s interrupt() method is executed, the task enters the ready state. The next time the task enters the running state, an InterruptedException is thrown.

 

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

 

136. What is the return type of a program’s main() method? 

A program’s main() method has a void return type.

 

137. Name four Container classes. 

Window, Frame, Dialog, FileDialog, Panel, Applet, or ScrollPane

 

138. What is the difference between a Choice and a List? 

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.

 

139. What class of exceptions are generated by the Java run-time system? 

The Java runtime system generates RuntimeException and Error exceptions.

 

140. What class allows you to read objects directly from a stream? 

The ObjectInputStream class supports the reading of objects from input streams.

 

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

 

142. Under what conditions is an object’s finalize() method invoked by the garbage collector? 

The garbage collector invokes an object’s finalize() method when it detects that the object has become unreachable.

 

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

 

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

 

145. What is the difference between the JDK 1.02 event model and the event-delegation  

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 event-delegation model is more efficient than the event-inheritance model because it eliminates the processing required to support the bubbling of unhandled events.

 

146. How is it possible for two String objects with identical values not to be equal  

under the == operator? 

The == operator compares two objects to determine if they are the same object in memory. It is possible for two String objects to have the same value, but located indifferent areas of memory.

 

147. Why are the methods of the Math class static? 

So they can be invoked as if they are a mathematical code library.

 

148. What Checkbox method allows you to tell if a Checkbox is checked? 

getState()

 

149. What state is a thread in when it is executing? 

An executing thread is in the running state.

 

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

 

151. How are the elements of a GridLayout organized? 

The elements of a GridBad layout are of equal size and are laid out using the squares of a grid.

 

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

 

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

 

 

154. What is the Set interface? 

The Set interface provides methods for accessing the elements of a finite mathematical set. Sets do not allow duplicate elements. 

 

155. What classes of exceptions may be thrown by a throw statement? 

A throw statement may throw any expression that may be assigned to the Throwable type.

 

156. What are E and PI? 

E is the base of the natural logarithm and PI is mathematical value pi.

 

157. Are true and false keywords? 

The values true and false are not keywords.

 

158. What is a void return type? 

A void return type indicates that a method does not return a value.

 

159. What is the purpose of the enableEvents() method? 

The enableEvents() method is used to enable an event for a particular object. Normally, an event is enabled when a listener is added to an object for a particular event. The enableEvents() method is used by objects that handle events by overriding their event-dispatch methods.

 

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

 

161. What happens when you add a double value to a String? 

The result is a String object.

 

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

 

163. Which package is always imported by default? 

The java.lang package is always imported by default.

 

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

 

165. How are this and super used? 

this is used to refer to the current object instance. super is used to refer to the variables and methods of the superclass of the current object instance.

 

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

 

167. What is a compilation unit? 

A compilation unit is a Java source code file.

 

168. What interface is extended by AWT event listeners? 

All AWT event listeners extend the java.util.EventListener interface.

 

 

 

169. What restrictions are placed on method overriding? 

Overridden methods must have the same name, argument list, and return type.

The overriding method may not limit the access of the method it overrides.

The overriding method may not throw any exceptions that may not be thrown

by the overridden method.

 

170. How can a dead thread be restarted? 

A dead thread cannot be restarted.

 

171. What happens if an exception is not caught? 

An uncaught exception results in the uncaughtException() method of the thread’s ThreadGroup being invoked, which eventually results in the termination of the program in which it is thrown.

 

172. What is a layout manager? 

A layout manager is an object that is used to organize components in a container.

 

173. Which arithmetic operations can result in the throwing of an ArithmeticException? 

Integer / and % can result in the throwing of an ArithmeticException.

 

174. What are three ways in which a thread can enter the waiting state? 

A thread can enter the waiting state by invoking its sleep() method, by blocking on I/O, by unsuccessfully attempting to acquire an object’s lock, or by invoking an object’s wait() method. It can also enter the waiting state by invoking its

(deprecated) suspend() method.

 

175. Can an abstract class be final? 

An abstract class may not be declared as final.

 

176. What is the ResourceBundle class? 

The ResourceBundle class is used to store locale-specific resources that can be loaded by a program to tailor the program’s appearance to the particular locale in which it is being run.

 

177. What happens if a try-catch-finally statement does not have a catch clause  

to handle an exception that is thrown within the body of the try statement? 

The exception propagates up to the next higher level try-catch statement (if any) or results in the program’s termination. 

 

178. What is numeric promotion? 

Numeric promotion is the conversion of a smaller numeric type to a larger numeric type, so that integer and floating-point operations may take place. In numerical promotion, byte, char, and short values are converted to int

values. The int values are also converted to long values, if necessary. The long and float values are converted to double values, as required.

 

179. What is the difference between a Scrollbar and a ScrollPane? 

A Scrollbar is a Component, but not a Container. A ScrollPane is a Container. A ScrollPane handles its own events and performs its own scrolling.

 

180. What is the difference between a public and a non-public class? 

A public class may be accessed outside of its package. A non-public class may not be accessed outside of its package.

 

181. To what value is a variable of the boolean type automatically initialized? 

The default value of the boolean type is false.

 

182. Can try statements be nested? 

Try statements may be tested.

 

 

 

183. What is the difference between the prefix and postfix forms of the ++ operator? 

The prefix form performs the increment operation and returns the value ofthe increment operation. The postfix form returns the current value all of the expression and then performs the increment operation on that value.

 

184. What is the purpose of a statement block? 

A statement block is used to organize a sequence of statements as a single statement group.

 

185. What is a Java package and how is it used? 

A Java package is a naming context for classes and interfaces. A package is used to create a separate name space for groups of classes and interfaces. Packages are also used to organize related classes and interfaces into a single API unit and to control accessibility to these classes and interfaces.

 

186. What modifiers may be used with a top-level class? 

A top-level class may be public, abstract, or final.

 

187. What are the Object and Class classes used for? 

The Object class is the highest-level class in the Java class hierarchy. The Class class is used to represent the classes and interfaces that are loaded by a Java program.

 

188. How does a try statement determine which catch clause should be used  

to handle an exception? 

When an exception is thrown within the body of a try statement, the catch clauses of the try statement are examined in the order in which they appear. The first catch clause that is capable of handling the exception is executed.

The remaining catch clauses are ignored.

 

189. Can an unreachable object become reachable again? 

An unreachable object may become reachable again. This can happen when the object’s finalize() method is invoked and the object performs an operation which causes it to become accessible to reachable objects.

 

190. When is an object subject to garbage collection? 

An object is subject to garbage collection when it becomes unreachable to the program in which it is used.

 

191. What method must be implemented by all threads? 

All tasks must implement the run() method, whether they are a subclass ofThread or implement the Runnable interface.

 

192. What methods are used to get and set the text label displayed by a Button object? 

getLabel() and setLabel()

 

193. Which Component subclass is used for drawing and painting? 

Canvas

 

194. What are synchronized methods and synchronized statements? 

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

 

195. What are the two basic ways in which classes that can be run as threads  

may be defined? 

A thread class may be declared as a subclass of Thread, or it may implement the Runnable interface.

 

196. What are the problems faced by Java programmers who don’t use layout managers? 

Without layout managers, Java programmers are faced with determining how their GUI will be displayed across multiple windowing systems and finding a common sizingand positioning that will work within the constraints imposed by each windowing system.

 

197. What is the difference between an if statement and a switch statement? 

The if statement is used to select among two alternatives. It uses a boolean expression to decide which alternative should be executed. The switch statement is used to select among multiple alternatives. It uses an int expression to determine which alternative should be executed.

 

198. What happens when you add a double value to a String? 

The result is a String object.

 

199. What is the List interface? 

The List interface provides support for ordered collections of objects.
 



No Comments »

Java Beans Interview Questions

July 2nd, 2006

QUESTION: What is a JavaBean?

ANSWER: JavaBeans are reusable software components written in the Java programming language, designed to be manipulated visually by a software develpoment environment, like JBuilder or VisualAge for Java. They are similar to Microsoft’s ActiveX components, but designed to be platform-neutral, running anywhere there is a Java Virtual Machine (JVM).

QUESTION: What are the seven layers(OSI model) of networking?

ANSWER: 1.Physical, 2.Data Link, 3.Network, 4.Transport, 5.Session, 6.Presentation and 7.Application Layers.

QUESTION: What are some advantages and disadvantages of Java Sockets?

ANSWER:
Advantages of Java Sockets:

Sockets are flexible and sufficient. Efficient socket based programming can be easily implemented for general communications.

Sockets cause low network traffic. Unlike HTML forms and CGI scripts that generate and transfer whole web pages for each new request, Java applets can send only necessary updated information.

Disadvantages of Java Sockets:

Security restrictions are sometimes overbearing because a Java applet running in a Web browser is only able to establish connections to the machine where it came from, and to nowhere else on the network

Despite all of the useful and helpful Java features, Socket based communications allows only to send packets of raw data between applications. Both the client-side and server-side have to provide mechanisms to make the data useful in any way.

Since the data formats and protocols remain application specific, the re-use of socket based implementations is limited.

QUESTION: What is the difference between a NULL pointer and a void pointer?

ANSWER: A NULL pointer is a pointer of any type whose value is zero. A void pointer is a pointer to an object of an unknown type, and is guaranteed to have enough bits to hold a pointer to any object. A void pointer is not guaranteed to have enough bits to point to a function (though in general practice it does).

QUESTION: What is encapsulation technique? 

ANSWER: Hiding data within the class and making it available only through the methods. This technique is used to protect your class against accidental changes to fields, which might leave the class in an inconsistent state.

What is a Servlet?

Answer: Servlets are modules of Java code that run in a server

application (hence the name “Servlets”, similar to “Applets”

on the client side) to answer client requests.

Question2:

What advantages does CMOS have over TTL(transitor transitor logic)?

Answer:

low power dissipation

pulls up to rail

easy to interface

Question3:

How is Java unlike C++? (Asked by Sun)

Answer:

Two classes of language features have been removed from C++ to make it Java. These are those language features which make C++ unsafe and those which make it hard to read.

Question4:

What is HTML (Hypertext Markup Language)?

Answer:

HTML (HyperText Markup Language) is the set of “markup” symbols or tags inserted in a file intended for display on a World Wide Web browser. The markup tells the Web browser how to display a Web page’s words and images for the user.

Question5:

what is class?

Answer: A class describes a collection of related objects.

Q: What are the most common techniques for reusing functionality in object-oriented systems?
A: The two most common techniques for reusing functionality in object-oriented systems are class inheritance and object composition.

Class inheritance lets you define the implementation of one class in terms of another’s. Reuse by subclassing is often referred to as white-box reuse.
Object composition is an alternative to class inheritance. Here, new functionality is obtained by assembling or composing objects to get more complex functionality. This is known as black-box reuse.

Q: Why would you want to have more than one catch block associated with a single try block in Java?
A: Since there are many things can go wrong to a single executed statement, we should have more than one catch(s) to catch any errors that might occur.

Q: What language is used by a relational model to describe the structure of a database?
A: The Data Definition Language.

Q: What is JSP? Describe its concept.
A: JSP is the JavaServer Page. The JavaServer Page concept is to provide an HTML document with the ability to plug in content at selected locations in the document. (This content is then supplied by the Web server along with the rest of the HTML document at the time the document is downloaded).

Q: What does the JSP engine do when presented with a JavaServer Page to process?
A: The JSP engine builds a servlet. The HTML portions of the JavaServer Page become Strings transmitted to print methods of a PrintWriter object. The JSP tag portions result in calls to methods of the appropriate JavaBean class whose output is translated into more calls to a println method to place the result in the HTML document.

Q:In Java, what is the difference between an Interface and an Abstract class?

A: An Abstract class declares have at least one instance method that is declared abstract which will be implemented by the subclasses. An abstract class can have instance methods that implement a default behavior. An Interface can only declare constants and instance methods, but cannot implement default behavior.

Q: Can you have virtual functions in Java? Yes or No. If yes, then what are virtual functions?

A: Yes, Java class functions are virtual by default. Virtual functions are functions of subclasses that can be invoked from a reference to their superclass. In other words, the functions of the actual object are called when a function is invoked on the reference to that object.

Q:Write a function to reverse a linked list p ?

A:

Link* reverse_list(Link* p)
{
if (p == NULL)
return NULL;

Link* h = p;
p = p->next;
h->next = NULL;
while (p != null)
{
Link* t = p->next;
p->next = h;
h = p;
p = t;
}
return h;
}
Q:In C++, what is the usefulness of Virtual destructors?A:Virtual destructors are neccessary to reclaim memory that were allocated for objects in the class hierarchy. If a pointer to a base class object is deleted, then the compiler guarantees the various subclass destructors are called in reverse order of the object construction chain.

Q:What are mutex and semaphore? What is the difference between them?

A:A mutex is a synchronization object that allows only one process or thread to access a critical code block. A semaphore on the other hand allows one or more processes or threads to access a critial code block. A semaphore is a multiple mutex.

Question 1: What is the three tier model?
Answer: It is the presentation, logic, backend
Question 2: Why do we have index table in the database?
Answer: Because the index table contain the information of the other tables. It will
be faster if we access the index table to find out what the other contain.
Question 3: Give an example of using JDBC access the database.
Answer:
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’)”);
state.close();
con.close();
}
catch(Exception e)
{
System.out.println(e);
}
Question 4: What is the different of an Applet and a Java Application
Answer: The applet doesn’t have the main function
Question 5: How do we pass a reference parameter to a function in Java?
Answer: 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.
.why you prefer Java?
Answer: write once ,run anywhere.

2. Name some of the classes which provide the functionality of collation?
Answer: collator, rulebased collator, collationkey, collationelement iterator.

3. Awt stands for? and what is it?
Answer: AWT stands for Abstract window tool kit. It is a is a package that provides an integrated set of classes to manage user interface components.
4. why a java program can not directly communicate with an ODBC driver?
Answer: Since ODBC API is written in C language and makes use of pointers which Java can not support.
5. Are servlets platform independent? If so Why? Also what is the most common application of servlets?
Answer: Yes, Because they are written in Java. The most common application of servlet is to access database and dynamically construct HTTP response
Q1: What are the advantages of OOPL?Ans: Object oriented programming languages directly represent the real life objects. The features of OOPL as inhreitance, polymorphism, encapsulation makes it powerful.

Q2: What do mean by polymorphisum, inheritance, encapsulation?

Ans: Polymorhisum: is a feature of OOPl that at run time depending upon the type of object the appropriate method is called.
Inheritance: is a feature of OOPL that represents the “is a” relationship between different objects(classes). Say in real life a manager is a employee. So in OOPL manger class is inherited from the employee class.
Encapsulation: is a feature of OOPL that is used to hide the information.

Q3: What do you mean by static methods?

Ans: By using the static method there is no need creating an object of that class to use that method. We can directly call that method on that class. For example, say class A has static function f(), then we can call f() function as A.f(). There is no need of creating an object of class A.

Q4: What do you mean by virtual methods?

Ans: virtual methods are used to use the polymorhism feature in C++. Say class A is inherited from class B. If we declare say fuction f() as virtual in class B and override the same function in class A then at runtime appropriate method of the class will be called depending upon the type of the object.

Q5: Given two tables Student(SID, Name, Course) and Level(SID, level) write the SQL statement to get the name and SID of the student who are taking course = 3 and at freshman level.

Ans: SELECT Student.name, Student.SID
FROM Student, Level
WHERE Student.SID = Level.SID
AND Level.Level = “freshman”
AND Student.Course = 3;

Q6: What are the disadvantages of using threads?

Ans: DeadLock.

Q1: Write the Java code to declare any constant (say gravitational constant) and to get its value

Ans: Class ABC
{
static final float GRAVITATIONAL_CONSTANT = 9.8;
public void getConstant()
{
system.out.println(”Gravitational_Constant: ” + GRAVITATIONAL_CONSTANT);
}
}
Q2: What do you mean by multiple inheritance in C++ ?

Ans: Multiple inheritance is a feature in C++ by which one class can be of different types. Say class teachingAssistant is inherited from two classes say teacher and Student.

Q3: Can you write Java code for declaration of multiple inheritance in Java ?

Ans: Class C extends A implements B
{
}

Question: What is an HTML tag?
Answer: An HTML tag is a syntactical construct in the HTML language that abbreviates specific instruction to be executed when the HTML script is loaded into a Web brower. It is like a method in Java, a function in C++, a procedure in Pascal, or a routine in FORTRAN.
Question: What is polymorphism?
Answer: In object-oriented programming, the term “polymorphism” refers to the ability of objects to take the form objects of difference classes.
Question: What is the difference between a component and a container?
Answer:
A component is an object, like a button or a sroll bar, that has a visual representation in a sreen window.
A container is a window-like component that can contain other components.
Every component has a unique container that directly contains it.
Question: What is the difference between a constructor and a method?
Answer:
A constructor is a member function of a class that is used to create objects of that class. It has the same name as the class itself, has no return type, and is invoked using the new operator.
A method is an ordinary member function of a class. It has its own name, a return type (which may be void), and is invoked using the dot operator.
Question: What are the advantages and disadvantages of using an AVL tree?

Answer:
The advantage of an AVL tree is that it is always balanced, guaranteeing the O(lgn) speed of the Binary Search algorithm.
The disadvantages the complex rotations used by the insertion and removal algorithms needed to maintain the tree’s balance.

Q: How would you make the following SQL statement run faster? SELECT * FROM TABLEA WHERE COL1=’A’ AND COL2=’B';
A: Make sure that COL1 and COL2 have indexes.
Find out which condition will return less values and use that as the first conditonal.

Q: What is Data Mining
A: Data Minig is the process of sifting through extremeley large amounts of Data to find trends or relevent information.

Q: Name the Seven layers in the OSI Model.
A: Appication, Presentation, Session, Transport, Network, Data Link, Phyiscal

Q: What is one way to view a unix network share on a Windows computer, within explorer
A: NFS, The Unix computer can be running a NFS Server Daemon.

Q: How would you find all the processes running on your computer.
A: Unix, is ps -ef or ps -aux depending on version.

Q: What is DHCP
A: DHCP is a way to dynamically assign IP address to computers. Dyanmic Host Configuration Protocol

Q: What is HTTP Tunneling
A: HTTP Tunneling is a security method that encryptes packets traveling throught the internet. Only the intended reciepent should be able to decrypt the packets. Can be used to Create Virtual Private Networks. (VPN)

Q: Scenario: You have 9 identical looking balls, however one ball is heavier than the others. You have two chances to use a balance. How do you find out which ball is the heaviest?
A: Split into groups of three, randomly choose two groups and use balance on them. If one group is heavier, then discard the other 6 balls. If the two groups are the same weight. The heavier ball must be in the group that was not on the scale. Now randomly choose two balls and test on balance. If they are the same weight, the heaviest ball is on one that was not tested. Else the heaviest ball is already known from the balance.

Q1: How can we store the information returned from querying the database? and if it is too big, how does it affect the performance?

Answ: In Java the return information will be stored in the ResultSet object. Yes, if the ResultSet is getting big, it will slow down the process and the performance as well. We can prevent this situation by give the program a simple but specific query statement.

Q2: What is index table and why we use it?

Answ: Index table are based on a sorted ordering of the values. Index table provides fast access time when searching.

Q3: In Java why we use exceptions?

Answ: Java uses exceptions as a way of signaling serious problems when you execute a program. One major benefit of having an error signaled by an exception is that it separates the code that deals with errors from the code that is executed when things are moving along smoothly. Another positive aspect of exceptions is that they provide a way of enforcing a response to particular errors.

UML Questions used by a software company
Q. What does “object-oriented” mean to you?
Q. Can you name the four phases of the Unified Process?
A. Inception
Elaboration
Construction
Transition
Q. What can you tell us about the different phases of the Unified Process?
Q. Talk about some OO/UML artifacts you have used. What did they mean to you? How did you apply them to yout project?
Q. What is a “use case”?
A. A complete end-to-end business process that satisfies the needs of a user.
Q. What are different categories of use cases?
A. Detail Level: - High level / Expanded
Task Level: - Super / Sub (Abstract; Equal Alternatives; Complete v. Partial)
Importance: - Primary / Secondary (use Secondary for exceptional processes)
Abstraction: - Essential / Real
Q. What is the difference between a real and essential use case?
A. essential - describes the “essence” of the problem; technology independent
real - good for GUI designing; shows problem as related to technology decisions
Q. What is polymorphism?
A. Different objects reacting to the same message differently.
Q. In a System Sequence Diagram, what is a System Event?
A. It is from the expanded use case. It is an actor action the system directly responds to.
Q. Give an example of a situation which a State Diagram could effectively model.
A. Think of a cake and its different stages through the baking process: dough, baked, burned.
Q. For what are Operations Contracts written?
A. System Events.
Q. In an Operations Contract’s postconditions, four types of activities are specified. What are they?
A. They are:
instances created
associations formed
associations broken
attributes changed
Q. What does an Operations Contract do?
A. Provides a snapshot of the System’s state before and after a System Event. It is not interested in the Event’s specific behavior.
Q. What does a Collaboration Diagram (or Sequence Event, depending on the process) model?
A. A System Event’s behavior.
Q. How does one model a class in a Collaboration Diagram? An instance?
A. A box will represent both; however, a class is written as MyClass whereas an instance is written as myInstance:MyClass.
Q. What are the three parts of a class in a Class Diagram?
A. Name, Attributes, Methods.
Q. In Analysis, we are interested in documenting concepts within the relevant problem domain. What is a concept?
A. A person, place, thing, or idea that relates to the problem domain. They are candidates for objects.
Q. Does a concept HAVE to become a class in Design?
A. No.
Q. In a Class Diagram, what does a line with an arrow from one class to another denote?
A. Attribute visibility.
Q. What are the four types of visibility between objects?
A. Local, parameter, attribute, global.
Q. Have you ever used any Design Patterns?
Q. When do you use inheritance as opposed to aggregation?
A. An aggregation is a “has a” relationship, and it is represented in the UML by a clear diamond. An example of an aggregate relation is Table of Contents and Chapter. A Table of Contents “has a” Chapter.
Q. When would I prefer to use composition rather than aggregation?
A. Composition is a stronger form of aggregation. The object which is “contained” in another object is expected to live and die with the object which “contains” it. Composition is represented in the UML by a darkened diamond. An example of a composite relation is a Book and Chapter. A Book “has a” Chapter, and the Chapter cannot exist without the Book.
Q. Is the UML a process, method, or notation?
A. It is a notation. A process is Objectory, Booch, OMT, or the Unified Process. A process and a notation together make an OO method.
Q. What are two uses for inheritance?
A. specialization - “IS A KIND OF” relationship
abstraction - pull a common concept out to a higher level to make it more generic
Q. When would you use an abstract base class
A. When you need to enforce a particular interface, but are not able or do not need to define behavior at the base class level.
Q. All containers are pretty well templatized now. Can you think of any current “example” (e.g., an algorithm) which is implemented via inheritance but might be more efficiently implemented using templates?
Q. Can you tell us some good principles to use in OOA&D?
A. NOTE: This is not a complete list, by any means, but we have listed the GRASP Patterns here for examples (these help assign responsibilities between objects):
Low coupling
High cohesion
Controller
Creator
Don’t Talk to Strangers
Pure Fabrication
Indirection
Polymorphism
Expert
Q. What are some practicle benefits we can gain from a well-designed OO system?
Databases

 

1. What is a Cartesian product? What causes it?

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

Java
1. How do you find the size of a java object (not the primitive type) ?

ANS. type cast it to string and find its s.length()

2. Why is multiple inheritance not provided in Java?

3. Thread t = new Thread(); t.start(); t = null; now what will happen to the created thread?

4. How is garbage collection done in java?

5. How do you write a “ping” routine in java?

6. What are the security restrictions on applets?

Linked lists
* 0. Under what circumstances can one delete an element from a singly linked list in constant time?

* 1. Given a singly linked list, determine whether it contains a loop or not.

2. Given a singly linked list, print out its contents in reverse order. Can you do it without using any extra space?

3. Given a binary tree with nodes, print out the values in pre-order/in-order/post-order without using any extra space.

4. Reverse a singly linked list recursively. The function prototype is node * reverse (node *) ;

5. Given a singly linked list, find the middle of the list.

Hints and Answers

0. If the list is circular and there are no references to the nodes in the list from anywhere else! Just copy the contents of the next node and delete the next node. If the list is not circular, we can delete any but the last node using this idea. In that case, mark the last node as dummy!

1. (a) Start reversing the list. If you reach the head, gotcha! there is a loop!

But this changes the list. So, reverse the list again.

(b) Maintain two pointers, initially pointing to the head. Advance one of them one node at a time. And the other one, two nodes at a time. If the latter overtakes the former at any time, there is a loop!

p1 = p2 = head;

do {
p1 = p1->next;
p2 = p2->next->next;
} while (p1 != p2);

2. Start reversing the list. Do this again, printing the contents.

3. [Yet to think about]

4. node * reverse (node * n)
{
node * m ;

if (! (n && n -> next))
return n ;

m = reverse (n -> next) ;
n -> next -> next = n ;
n -> next = NULL ;
return m ;
}

5. Use the single and double pointer jumping. Maintain two pointers, initially pointing to the head. Advance one of them one node at a time. And the other one, two nodes at a time. When the double reaches the end, the single is in the middle. This is not asymptotically faster but seems to take less steps than going through the list twice.

Puzzles, Riddles and Others
0. Classic: If a bear walks one mile south, turns left and walks one mile to the east and then turns left again and walks one mile north and arrives at its original position, what is the color of the bear.

ANS. The color of the bear is trivial. The possible solutions to it are interesting. In addition to the trivial north pole and circle near north pole solutions, there is an additional circle near south pole solution. Think it out.

* 1. Given a rectangular (cuboidal for the puritans) cake with a rectangular piece removed (any size or orientation), how would you cut the remainder of the cake into two equal halves with one straight cut of a knife?

ANS. Join the centers of the original and the removed rectangle. It works for cuboids too!

2. There are 3 baskets. one of them have apples, one has oranges only and the other has mixture of apples and oranges. The labels on their baskets always lie. (i.e. if the label says oranges, you are sure that it doesn’t have oranges only,it could be a mixture) The task is to pick one basket and pick only one fruit from it and then correctly label all the three baskets.

HINT. There are only two combinations of distributions in which ALL the baskets have wrong labels. By picking a fruit from the one labeled MIXTURE, it is possible to tell what the other two baskets have.

3. You have 8 balls. One of them is defective and weighs less than others. You have a balance to measure balls against each other. In 2 weighings how do you find the defective one?

4. Why is a manhole cover round?

HINT. The diagonal of a square hole is larger than the side of a cover!

Alternate answers: 1. Round covers can be transported by one person, because they can be rolled on their edge. 2. A round cover doesn’t need to be rotated to fit over a hole.

5. How many cars are there in the USA?

6. You’ve got someone working for you for seven days and a gold bar to pay them. The gold bar is segmented into seven connected pieces. You must give them a piece of gold at the end of every day. If you are only allowed to make two breaks in the gold bar, how do you pay your worker?

7. One train leaves Los Angeles at 15mph heading for New York. Another train leaves from New York at 20mph heading for Los Angeles on the same track. If a bird, flying at 25mph, leaves from Los Angeles at the same time as the train and flies back and forth between the two trains until they collide, how far will the bird have traveled?

HINT. Think relative speed of the trains.

8. You have two jars, 50 red marbles and 50 blue marbles. A jar will be picked at random, and then a marble will be picked from the jar. Placing all of the marbles in the jars, how can you maximize the chances of a red marble being picked? What are the exact odds of getting a red marble using your scheme?

9. Imagine you are standing in front of a mirror, facing it. Raise your left hand. Raise your right hand. Look at your reflection. When you raise your left hand your reflection raises what appears to be his right hand. But when you tilt your head up, your reflection does too, and does not appear to tilt his/her head down. Why is it that the mirror appears to reverse left and right, but not up and down?

10. You have 5 jars of pills. Each pill weighs 10 gram, except for contaminated pills contained in one jar, where each pill weighs 9 gm. Given a scale, how could you tell which jar had the contaminated pills in just one measurement?

ANS. 1. Mark the jars with numbers 1, 2, 3, 4, and 5.
2. Take 1 pill from jar 1, take 2 pills from jar 2, take 3 pills from jar 3, take 4 pills from jar 4 and take 5 pills from jar 5.
3. Put all of them on the scale at once and take the measurement.
4. Now, subtract the measurment from 150 ( 1*10 + 2*10 + 3*10 + 4*10 + 5*10)
5. The result will give you the jar number which has contaminated pill.

11. If you had an infinite supply of water and a 5 quart and 3 quart pail, how would you measure exactly 4 quarts?

12. You have a bucket of jelly beans. Some are red, some are blue, and some green. With your eyes closed, pick out 2 of a like color. How many do you have to grab to be sure you have 2 of the same?

13. Which way should the key turn in a car door to unlock it?

14. If you could remove any of the 50 states, which state would it be and why?

15. There are four dogs/ants/people at four corners of a square of unit distance. At the same instant all of them start running with unit speed towards the person on their clockwise direction and will always run towards that target. How long does it take for them to meet and where?

HINT. They will meet in the centre and the distance covered by them is independent of the path they actually take (a spiral).

16. (fram Tara Hovel) A helicopter drops two trains, each on a parachute, onto a straight infinite railway line. There is an undefined distance between the two trains. Each faces the same direction, and upon landing, the parachute attached to each train falls to the ground next to the train and detaches. Each train has a microchip that controls its motion. The chips are identical. There is no way for the trains to know where they are. You need to write the code in the chip to make the trains bump into each other. Each line of code takes a single clock cycle to execute.
You can use the following commands (and only these);
MF - moves the train forward
MB - moves the train backward
IF (P) - conditional that’s satisfied if the train is next to a parachute. There is no “then” to this IF statement.
GOTO

ANS.
A: MF
IF (P)
GOTO B
GOTO A
—–
B: MF
GOTO B
Explanation: The first line simply gets them off the parachutes. You need to get the trains off their parachutes so the back train can find the front train’s parachute, creating a special condition that will allow it to break out of the code they both have to follow initially. They both loop through A: until the back train finds the front train’s parachute, at which point it goes to B: and gets stuck in that loop. The front train still hasn’t found a parachute, so it keeps in the A loop. Because each line of code takes a “clock cycle” to execute, it takes longer to execute the A loop than the B loop, therefore the back train (running in the B loop) will catch up to the front train.

  • What is normalization? Explain different levels of normalization?
  • Check out the article Q100139 from Microsoft knowledge base and of course, there’s much more information available in the net. It’ll be a good idea to get a hold of any RDBMS fundamentals text book, especially the one by C. J. Date. Most of the times, it will be okay if you can explain till third normal form.
  • What is denormalization and when would you go for it?
    • As the name indicates, denormalization is the reverse process of normalization. It’s the controlled introduction of redundancy in to the database design. It helps improve the query performance as the number of joins could be reduced.
  • How do you implement one-to-one, one-to-many and many-to-many relationships while designing tables?
    • One-to-One relationship can be implemented as a single table and rarely as two tables with primary and foreign key relationships. One-to-Many relationships are implemented by splitting the data into two tables with primary key and foreign key relationships. Many-to-Many relationships are implemented using a junction table with the keys from both the tables forming the composite primary key of the junction table. It will be a good idea to read up a database designing fundamentals text book.
  • What’s the difference between a primary key and a unique key?
    • Both primary key and unique enforce uniqueness of the column on which they are defined. But by default primary key creates a clustered index on the column, where are unique creates a nonclustered index by default. Another major difference is that, primary key doesn’t allow NULLs, but unique key allows one NULL only.
  • What are user defined datatypes and when you should go for them?
    • User defined datatypes let you extend the base SQL Server datatypes by providing a descriptive name, and format to the database. Take for example, in your database, there is a column called Flight_Num which appears in many tables. In all these tables it should be varchar(8). In this case you could create a user defined datatype called Flight_num_type of varchar(8) and use it across all your tables. See sp_addtype, sp_droptype in books online.
  • What is bit datatype and what’s the information that can be stored inside a bit column?
    • Bit datatype is used to store boolean information like 1 or 0 (true or false). Untill SQL Server 6.5 bit datatype could hold either a 1 or 0 and there was no support for NULL. But from SQL Server 7.0 onwards, bit datatype can represent a third state, which is NULL.
  • Define candidate key, alternate key, composite key.
    • A candidate key is one that can identify each row of a table uniquely. Generally a candidate key becomes the primary key of the table. If the table has more than one candidate key, one of them will become the primary key, and the rest are called alternate keys. A key formed by combining at least two or more columns is called composite key.
  • What are defaults? Is there a column to which a default can’t be bound?
    • A default is a value that will be used by a column, if no value is supplied to that column while inserting data. IDENTITY columns and timestamp columns can’t have defaults bound to them. See CREATE DEFAULT in books online.
  • What is a transaction and what are ACID properties?
    • A transaction is a logical unit of work in which, all the steps must be performed or none. ACID stands for Atomicity, Consistency, Isolation, Durability. These are the properties of a transaction. For more information and explanation of these properties, see SQL Server books online or any RDBMS fundamentals text book. Explain different isolation levels An isolation level determines the degree of isolation of data between concurrent transactions. The default SQL Server isolation level is Read Committed. Here are the other isolation levels (in the ascending order of isolation): Read Uncommitted, Read Committed, Repeatable Read, Serializable. See SQL Server books online for an explanation of the isolation levels. Be sure to read about SET TRANSACTION ISOLATION LEVEL, which lets you customize the isolation level at the connection level. Read Committed - A transaction operating at the Read Committed level cannot see changes made by other transactions until those transactions are committed. At this level of isolation, dirty reads are not possible but nonrepeatable reads and phantoms are possible. Read Uncommitted - A transaction operating at the Read Uncommitted level can see uncommitted changes made by other transactions. At this level of isolation, dirty reads, nonrepeatable reads, and phantoms are all possible. Repeatable Read - A transaction operating at the Repeatable Read level is guaranteed not to see any changes made by other transactions in values it has already read. At this level of isolation, dirty reads and nonrepeatable reads are not possible but phantoms are possible. Serializabl