Search

Complete reference to core java interview questions basic to advanced level : SE to Team Lead level Part - 12


Q:
What is the difference between an Interface and an Abstract class?
A:
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 and all methods are implicitly abstract. An interface has all public members and no implementation. An abstract class is a class which may have the usual flavors of class members (private, protected, etc.), but has some abstract methods.
.


Q:
What is the purpose of garbage collection in Java, and when is it used?
A:
The purpose of garbage collection is to identify and discard objects that are no longer needed by a program so that their resources can be reclaimed and reused. A Java object is subject to garbage collection when it becomes unreachable to the program in which it is used.


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


Q:
Explain different way of using thread?
A:
The thread could be implemented by using runnable interface or by inheriting from the Thread class. The former is more advantageous, 'cause when you are going for multiple inheritance..the only interface can help.


Q:
What are pass by reference and passby value?
A:
Pass By Reference means the passing the address itself rather than passing the value. Passby Value means passing a copy of the value to be passed. 


Q:
What is HashMap and Map?
A:
Map is Interface and Hashmap is class that implements that.


Q:
Difference between HashMap and HashTable?
A:
The HashMap class is roughly equivalent to Hashtable, except that it is unsynchronized and permits nulls. (HashMap allows null values as key and value whereas Hashtable doesnt allow). HashMap does not guarantee that the order of the map will remain constant over time. HashMap is unsynchronized and Hashtable is synchronized.


Q:
Difference between Vector and ArrayList?
A:
Vector is synchronized whereas arraylist is not.


Q:
Difference between Swing and Awt?
A:
AWT are heavy-weight componenets. Swings are light-weight components. Hence swing works faster than AWT.


Q:
What is the difference between a constructor and a method?
A:
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.


Q:
What is an Iterator?
A:
Some of the collection classes provide traversal of their contents via a java.util.Iterator interface. This interface allows you to walk through a collection of objects, operating on each object in turn. Remember when using Iterators that they contain a snapshot of the collection at the time the Iterator was obtained; generally it is not advisable to modify the collection itself while traversing an Iterator.


Q:
State the significance of public, private, protected, default modifiers both singly and in combination and state the effect of package relationships on declared items qualified by these modifiers.
A:
public : Public class is visible in other packages, field is visible everywhere (class must be public too)
private : Private variables or methods may be used only by an instance of the same class that declares the variable or method, A private feature may only be accessed by the class that owns the feature.
protected : Is available to all classes in the same package and also available to all subclasses of the class that owns the protected feature.This access is provided even to subclasses that reside in a different package from the class that owns the protected feature.
default :What you get by default ie, without any access modifier (ie, public private or protected).It means that it is visible to all within a particular package.


Q:
What is an abstract class?
A:
Abstract class must be extended/subclassed (to be useful). It serves as a template. A class that is abstract may not be instantiated (ie, you may not call its constructor), abstract class may contain static data. Any class with an abstract method is automatically abstract itself, and must be declared as such.
A class may be declared abstract even if it has no abstract methods. This prevents it from being instantiated.


Q:
What is static in java?
A:
Static means one per class, not one for each object no matter how many instance of a class might exist. This means that you can use them without creating an instance of a class.Static methods are implicitly final, because overriding is done based on the type of the object, and static methods are attached to a class, not an object. A static method in a superclass can be shadowed by another static method in a subclass, as long as the original method was not declared final. However, you can't override a static method with a nonstatic method. In other words, you can't change a static method into an instance method in a subclass.


Q:
What is final?
A:
A final class can't be extended ie., final class may not be subclassed. A final method can't be overridden when its class is inherited. You can't change value of a final variable (is a constant).

Q:
What if the main method is declared as private?
A:
The program compiles properly but at runtime it will give "Main method not public." message.



Q:
What if the static modifier is removed from the signature of the main method?
A:
Program compiles. But at runtime throws an error "NoSuchMethodError".



Q:
What if I write static public void instead of public static void?
A:
Program compiles and runs properly.



Q:
What if I do not provide the String array as the argument to the method?
A:
Program compiles but throws a runtime error "NoSuchMethodError".



Q:
What is the first argument of the String array in main method?
A:
The String array is empty. It does not have any element. This is unlike C/C++ where the first element by default is the program name.



Q:
If I do not provide any arguments on the command line, then the String array of Main method will be empty or null?
A:
It is empty. But not null.



Q:
How can one prove that the array is not null but empty using one line of code?
A:
Print args.length. It will print 0. That means it is empty. But if it would have been null then it would have thrown a NullPointerException on attempting to print args.length.



Q:
What environment variables do I need to set on my machine in order to be able to run Java programs?
A:
CLASSPATH and PATH are the two variables.



Q:
Can an application have multiple classes having main method?
A:
Yes it is possible. While starting the application we mention the class name to be run. The JVM will look for the Main method only in the class whose name you have mentioned. Hence there is not conflict amongst the multiple classes having main method.



Q:
Can I have multiple main methods in the same class?
A:
No the program fails to compile. The compiler says that the main method is already defined in the class.



Q:
Do I need to import java.lang package any time? Why ?
A:
No. It is by default loaded internally by the JVM.



Q:
Can I import same package/class twice? Will the JVM load the package twice at runtime?
A:
One can import the same package or same class multiple times. Neither compiler nor JVM complains abt it. And the JVM will internally load the class only once no matter how many times you import the same class.



Q:
What are Checked and UnChecked Exception?
A:
A checked exception is some subclass of Exception (or Exception itself), excluding class RuntimeException and its subclasses.
Making an exception checked forces client programmers to deal with the possibility that the exception will be thrown. eg, IOException thrown by java.io.FileInputStream's read() method·
Unchecked exceptions are RuntimeException and any of its subclasses. Class Error and its subclasses also are unchecked. With an unchecked exception, however, the compiler doesn't force client programmers either to catch the
exception or declare it in a throws clause. In fact, client programmers may not even know that the exception could be thrown. eg, StringIndexOutOfBoundsException thrown by String's charAt() method· Checked exceptions must be caught at compile time. Runtime exceptions do not need to be. Errors often cannot be.


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


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

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

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

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

Q:
Are the imports checked for validity at compile time? e.g. will the code containing an import such as java.lang.ABCD compile?
A:
Yes the imports are checked for the semantic validity at compile time. The code containing above line of import will not compile. It will throw an error saying,can not resolve symbol
symbol : class ABCD
location: package io
import java.io.ABCD;



Q:
Does importing a package imports the subpackages as well? e.g. Does importing com.MyTest.* also import com.MyTest.UnitTests.*?
A:
No you will have to import the subpackages explicitly. Importing com.MyTest.* will import classes in the package MyTest only. It will not import any class in any of it's subpackage.



Q:
What is the difference between declaring a variable and defining a variable?
A:
In declaration we just mention the type of the variable and it's name. We do not initialize it. But defining means declaration + initialization.
e.g String s; is just a declaration while String s = new String ("abcd"); Or String s = "abcd"; are both definitions.



Q:
What is the default value of an object reference declared as an instance variable?
A:
null unless we define it explicitly.



Q:
Can a top level class be private or protected?
A:
No. A top level class can not be private or protected. It can have either "public" or no modifier. If it does not have a modifier it is supposed to have a default access.If a top level class is declared as private the compiler will complain that the "modifier private is not allowed here". This means that a top level class can not be private. Same is the case with protected.



Q:
What type of parameter passing does Java support?
A:
In Java the arguments are always passed by value .

[ Update from Eki and Jyothish Venu]

Q:
Primitive data types are passed by reference or pass by value?
A:
Primitive data types are passed by value.



Q:
Objects are passed by value or by reference?
A:
Java only supports pass by value. With objects, the object reference itself is passed by value and so both the original reference and parameter copy both refer to the same object .

[ Update from Eki and Jyothish Venu]

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



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



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



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



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



Q:
What is Externalizable interface?
A:
Externalizable is an interface which contains two methods readExternal and writeExternal. These methods give you a control over the serialization mechanism. Thus if your class implements this interface, you can customize the serialization process by implementing these methods.



Q:
When you serialize an object, what happens to the object references included in the object?
A:
The serialization mechanism generates an object graph for serialization. Thus it determines whether the included object references are serializable or not. This is a recursive process. Thus when an object is serialized, all the included objects are also serialized alongwith the original obect.



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



Q:
What happens to the static fields of a class during serialization?
A:
There are three exceptions in which serialization doesnot necessarily read and write to the stream. These are
1. Serialization ignores static fields, because they are not part of ay particular state state.
2. Base class fields are only hendled if the base class itself is serializable.
3. Transient fields.

JSP Interview Questions

Q:
What is a output comment?
A:
A comment that is sent to the client in the viewable page source.The JSP engine handles an output comment as uninterpreted HTML text, returning the comment in the HTML output sent to the client. You can see the comment by viewing the page source from your Web browser.
JSP Syntax
<!-- comment [ <%= expression %> ] -->

Example 1
<!-- This is a commnet sent to client on
<%= (new java.util.Date()).toLocaleString() %>
-->

Displays in the page source:
<!-- This is a commnet sent to client on January 24, 2004 -->


Q:
What is a Hidden Comment?
A:
A comments that documents the JSP page but is not sent to the client. The JSP engine ignores a hidden comment, and does not process any code within hidden comment tags. A hidden comment is not sent to the client, either in the displayed JSP page or the HTML page source. The hidden comment is useful when you want to hide or "comment out" part of your JSP page.
You can use any characters in the body of the comment except the closing --%> combination. If you need to use --%> in your comment, you can escape it by typing --%\>.
JSP Syntax
<%-- comment --%>
Examples
<%@ page language="java" %>
<html>
<head><title>A Hidden Comment </title></head>
<body>
<%-- This comment will not be visible to the colent in the page source --%>
</body>
</html>


Q:
What is a Expression?
A:
An expression tag contains a scripting language expression that is evaluated, converted to a String, and inserted where the expression appears in the JSP file. Because the value of an expression is converted to a String, you can use an expression within text in a JSP file. Like
<%= someexpression %>

<%= (new java.util.Date()).toLocaleString() %>
You cannot use a semicolon to end an expression


Q:
What is a Declaration?
A:
A declaration declares one or more variables or methods for use later in the JSP source file.
A declaration must contain at least one complete declarative statement. You can declare any number of variables or methods within one declaration tag, as long as they are separated by semicolons. The declaration must be valid in the scripting language used in the JSP file.

<%! somedeclarations %>
<%! int i = 0; %>
<%! int a, b, c; %>


Q:
What is a Scriptlet?
A:
A scriptlet can contain any number of language statements, variable or method declarations, or expressions that are valid in the page scripting language.Within scriptlet tags, you can
1.Declare variables or methods to use later in the file (see also Declaration).

2.Write expressions valid in the page scripting language (see also Expression).

3.Use any of the JSP implicit objects or any object declared with a <jsp:useBean> tag.
You must write plain text, HTML-encoded text, or other JSP tags outside the scriptlet.
Scriptlets are executed at request time, when the JSP engine processes the client request. If the scriptlet produces output, the output is stored in the out object, from which you can display it.


Q:
What are implicit objects? List them?
A:
Certain objects that are available for the use in JSP documents without being declared first. These objects are parsed by the JSP engine and inserted into the generated servlet. The implicit objects re listed below
  • request
  • response
  • pageContext
  • session
  • application
  • out
  • config
  • page
  • exception


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


Q:
What are the different scope valiues for the <jsp:useBean>?
A:
The different scope values for <jsp:useBean> are
1. page
2. request
3.session
4.application


Q:
Explain the life-cycle mehtods in JSP?
A:
THe generated servlet class for a JSP page implements the HttpJspPage interface of the javax.servlet.jsp package. Hte HttpJspPage interface extends the JspPage interface which inturn extends the Servlet interface of the javax.servlet package. the generated servlet class thus implements all the methods of the these three interfaces. The JspPage interface declares only two mehtods - jspInit() and jspDestroy() that must be implemented by all JSP pages regardless of the client-server protocol. However the JSP specification has provided the HttpJspPage interfaec specifically for the JSp pages serving HTTP requests. This interface declares one method _jspService().
The jspInit()- The container calls the jspInit() to initialize te servlet instance.It is called before any other method, and is called only once for a servlet instance.
The _jspservice()- The container calls the _jspservice() for each request, passing it the request and the response objects.
The jspDestroy()- The container calls this when it decides take the instance out of service. It is the last method called n the servlet instance.


Q:
How do I prevent the output of my JSP or Servlet pages from being cached by the browser?
A:
You will need to set the appropriate HTTP header attributes to prevent the dynamic content output by the JSP page from being cached by the browser. Just execute the following scriptlet at the beginning of your JSP pages to prevent them from being cached at the browser. You need both the statements to take care of some of the older browser versions.
<%
response.setHeader("Cache-Control","no-store"); //HTTP 1.1
response.setHeader("Pragma\","no-cache"); //HTTP 1.0
response.setDateHeader ("Expires", 0); //prevents caching at the proxy server
%>

[ Received from Sumit Dhamija ]

Q:
How does JSP handle run-time exceptions?
A:
You can use the errorPage attribute of the page directive to have uncaught run-time exceptions automatically forwarded to an error processing page. For example:
<%@ page errorPage=\"error.jsp\" %> redirects the browser to the JSP page error.jsp if an uncaught exception is encountered during request processing. Within error.jsp, if you indicate that it is an error-processing page, via the directive: <%@ page isErrorPage=\"true\" %> Throwable object describing the exception may be accessed within the error page via the exception implicit object. Note: You must always use a relative URL as the value for the errorPage attribute.

[ Received from Sumit Dhamija ]

Q:
How can I implement a thread-safe JSP page? What are the advantages and Disadvantages of using it?
A:
You can make your JSPs thread-safe by having them implement the SingleThreadModel interface. This is done by adding the directive <%@ page isThreadSafe="false" %> within your JSP page. With this, instead of a single instance of the servlet generated for your JSP page loaded in memory, you will have N instances of the servlet loaded and initialized, with the service method of each instance effectively synchronized. You can typically control the number of instances (N) that are instantiated for all servlets implementing SingleThreadModel through the admin screen for your JSP engine. More importantly, avoid using the tag for variables. If you do use this tag, then you should set isThreadSafe to true, as mentioned above. Otherwise, all requests to that page will access those variables, causing a nasty race condition. SingleThreadModel is not recommended for normal use. There are many pitfalls, including the example above of not being able to use <%! %>. You should try really hard to make them thread-safe the old fashioned way: by making them thread-safe .

[ Received from Sumit Dhamija ]

Q:
How do I use a scriptlet to initialize a newly instantiated bean?
A:
A jsp:useBean action may optionally have a body. If the body is specified, its contents will be automatically invoked when the specified bean is instantiated. Typically, the body will contain scriptlets or jsp:setProperty tags to initialize the newly instantiated bean, although you are not restricted to using those alone.
The following example shows the “today” property of the Foo bean initialized to the current date when it is instantiated. Note that here, we make use of a JSP expression within the jsp:setProperty action.

<jsp:useBean id="foo" class="com.Bar.Foo" >
<jsp:setProperty name="foo" property="today"
value="<%=java.text.DateFormat.getDateInstance().format(new java.util.Date()) %>" / >
<%-- scriptlets calling bean setter methods go here --%>
</jsp:useBean >

[ Received from Sumit Dhamija ]

Q:
How can I prevent the word "null" from appearing in my HTML input text fields when I populate them with a resultset that has null values?
A:
You could make a simple wrapper function, like
<%!
String blanknull(String s) {
return (s == null) ? \"\" : s;
}
%>
then use it inside your JSP form, like
<input type="text" name="lastName" value="<%=blanknull(lastName)% >" >

[ Received from Sumit Dhamija ]

Q:
What's a better approach for enabling thread-safe servlets and JSPs? SingleThreadModel Interface or Synchronization?
A:
Although the SingleThreadModel technique is easy to use, and works well for low volume sites, it does not scale well. If you anticipate your users to increase in the future, you may be better off implementing explicit synchronization for your shared data. The key however, is to effectively minimize the amount of code that is synchronzied so that you take maximum advantage of multithreading.
Also, note that SingleThreadModel is pretty resource intensive from the server\'s perspective. The most serious issue however is when the number of concurrent requests exhaust the servlet instance pool. In that case, all the unserviced requests are queued until something becomes free - which results in poor performance. Since the usage is non-deterministic, it may not help much even if you did add more memory and increased the size of the instance pool.

[ Received from Sumit Dhamija ]

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

Consider the following example, in which two JSP files, say hello1.jsp and hello2.jsp, interact with each other. Basically, we create a new session within hello1.jsp and place an object within this session. The user can then traverse to hello2.jsp by clicking on the link present within the page. Within hello2.jsp, we simply extract the object that was earlier placed in the session and display its contents. Notice that we invoke the encodeURL() within hello1.jsp on the link used to invoke hello2.jsp; if cookies are disabled, the session ID is automatically appended to the URL, allowing hello2.jsp to still retrieve the session object. Try this example first with cookies enabled. Then disable cookie support, restart the brower, and try again. Each time you should see the maintenance of the session across pages. Do note that to get this example to work with cookies disabled at the browser, your JSP engine has to support URL rewriting.
hello1.jsp
<%@ page session=\"true\" %>
<%
Integer num = new Integer(100);
session.putValue("num",num);
String url =response.encodeURL("hello2.jsp");
%>
<a href=\'<%=url%>\'>hello2.jsp</a>
hello2.jsp
<%@ page session="true" %>
<%
Integer i= (Integer )session.getValue("num");
out.println("Num value in session is " + i.intValue());
%>

[ Received from Vishal Khasgiwala ]
Q:
What is the difference b/w variable declared inside a declaration part and variable declared in scriplet part?
A:
Variable declared inside declaration part is treated as a global variable.that means after convertion jsp file into servlet that variable will be in outside of service method or it will be declared as instance variable.And the scope is available to complete jsp and to complete in the converted servlet class.where as if u declare a variable inside a scriplet that variable will be declared inside a service method and the scope is with in the service method.

[ Received from Neelam Gangadhar]

Q:
Is there a way to execute a JSP from the comandline or from my own application?
A:
There is a little tool called JSPExecutor that allows you to do just that. The developers (Hendrik Schreiber <hs@webapp.de> & Peter Rossbach <pr@webapp.de>) aim was not to write a full blown servlet engine, but to provide means to use JSP for generating source code or reports. Therefore most HTTP-specific features (headers, sessions, etc) are not implemented, i.e. no reponseline or header is generated. Nevertheless you can use it to precompile JSP for your website.
Struts
Struts is a open source framework which make building of the web applications easier based on the java Servlet and JavaServer pages technologies.

Struts framework was created by Craig R. McClanahan and donated to the Apache Software Foundation in 2000. The Project now has several committers, and many developers are contributing to overall to the framework.

Developing web application using struts frame work is fairly complex, but it eases things after it is setup. It encourages software development following the MVC design pattern. Many web applications are JSP-only or Servlets-only. With JSP and Servlets, Java code is embedded in the HTML code and the Java code calls println methods to generate the HTML code respectively. Both approaches have their advantages and drawbacks; Struts gathers their strengths to get the best of their association.
Struts is based on Model-View-Controller (MVC) design paradigm, it is an implementation of JSP Model 2 Architecture. For more of Model-View-Controller (MVC) click here.

Consists of 8 Top-Level Packagesand approx 250 Classes and Interfaces.

Struts is a set of cooperating classes, servlets, and JSP tags that make up a reusable MVC 2 design. This definition implies that Struts is a framework, rather than a library, but Struts also contains an extensive tag library and utility classes that work independently of the framework.

The overview of struts
Client browser
An HTTP request from the client browser creates an event. The Web container will respond with an HTTP response.

Controller
The controller is responsible for intercepting and translating user input into actions to
be performed by the model. The controller is responsible for selecting the next view based on user input and the outcome of model operations.The Controller receives the request from the browser, and makes the decision where to send the request. With Struts, the Controller is a command design pattern implemented as a servlet. The struts-config.xml file configures the Controller.


Business logic
The business logic updates the state of the model and helps control the flow of the application. With Struts this is done with an Action class as a thin wrapper to the actual business logic.

Model
A model represents an application’s data and contains the logic for accessing and manipulating that data. Any data that is part of the persistent state of the application should reside in the model objects. The business objects update the application state. ActionForm bean represents the Model state at a session or request level, and not at a persistent level. Model services are accessed by the controller for either querying or effecting a change in the model state. The model notifies the view when a state change occurs in the model.The JSP file reads information from the ActionForm bean using JSP tags.

View
The view is responsible for rendering the state of the model. The presentation semantics are encapsulated within the view, therefore model data can be adapted for several different kinds of clients.The view modifies itself when a change in the model is communicated to the view. A view forwards user input to the controller.The view is simply a JSP file. There is no flow logic, no business logic, and no model information -- just tags. Tags are one of the thin
Struts 1.0 and 1.1
The new features added to Struts 1.1 are
1.
RequestProcessor class
2.
Method perform() replaced by execute() in Struts base Action Class
3.
4.
5.
6.
7.
8.
9
10.
11.
12.
13.
Changes to web.xml and struts-config.xml
Declarative exception handling
Dynamic ActionForms
Plug-ins
Multiple Application Modules
Nested Tags
The Struts Validator
Change to the ORO package
Change to Commons logging
Removal of Admin actions
Deprecation of the GenericDataSource
gs
Struts Controller
The controller is responsible for intercepting and translating user input into actions to be performed by the model. The controller is responsible for selecting the next view based on user input and the outcome of model operations. The Controller receives the request from the browser, invoke a business operation and coordinating the view to return to the client.

The controller is implemented by a java servlet, this servlet is centralized point of control for the web application. In struts framework the controller responsibilities are implemented by several different components like
The ActionServlet Class
The RequestProcessor Class
The Action Class

The ActionServlet extends the javax.servlet.http.httpServlet class. The ActionServlet class is not abstract and therefore can be used as a concrete controller by your application.
The controller is implemented by the ActionServlet class. All incoming requests are mapped to the central controller in the deployment descriptor as follows.
<servlet>

<servlet-name>action</servlet-name>

<servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
</servlet>


All request URIs with the pattern *.do are mapped to this servlet in the deployment descriptor as follows.
<servlet-mapping>

<servlet-name>action</servlet-name>

<url-pattern>*.do</url-pattern>
<url-pattern>*.do</url-pattern>
A request URI that matches this pattern will have the following form.
http://www.my_site_name.com/mycontext/actionName.do

The preceding mapping is called extension mapping, however, you can also specify path mapping where a pattern ends with /* as shown below.
<servlet-mapping>

<servlet-name>action</servlet-name>

<url-pattern>/do/*</url-pattern>
<url-pattern>*.do</url-pattern>
A request URI that matches this pattern will have the following form.
http://www.my_site_name.com/mycontext/do/action_Name
The class org.apache.struts.action.requestProcessor process the request from the controller. You can sublass the RequestProcessor with your own version and modify how the request is processed.

Once the controller receives a client request, it delegates the handling of the request to a helper class. This helper knows how to execute the business operation associated with the requested action. In the Struts framework this helper class is descended of
org.apache.struts.action.Action class. It acts as a bridge between a client-side user action and business operation. The Action class decouples the client request from the business model. This decoupling allows for more than one-to-one mapping between the user request and an action. The Action class also can perform other functions such as authorization, logging before invoking business operation. the Struts Action class contains several methods, but most important method is the execute() method.
public ActionForward execute(ActionMapping mapping,

ActionForm form, HttpServletRequest request, HttpServletResponse response)
throws Exception;

The execute() method is called by the controller when a request is received from a client. The controller creates an instance of the Action class if one doesn’t already exist. The strut framework will create only a single instance of each Action class in your application.

Action are mapped in the struts configuration file and this configuration is loaded into memory at startup and made available to the framework at runtime. Each Action element is represented in memory by an instance of the org.apache.struts.action.ActionMapping class . The ActionMapping object contains a path attribute that is matched against a portion of the URI of the incoming request.
<action>

path= "/somerequest"

type="com.somepackage.someAction"

scope="request"

name="someForm"

validate="true"

input="somejsp.jsp"

<forward name="Success" path="/action/xys" redirect="true"/>

<forward name="Failure" path="/somejsp.jsp" redirect="true"/>
</action>
Once this is done the controller should determine which view to return to the client. The execute method signature in Action class has a return type org.apache.struts.action.ActionForward class. The ActionForward class represents a destination to which the controller may send control once an action has completed. Instead of specifying an actual JSP page in the code, you can declaratively associate as action forward through out the application. The action forward are specified in the configuration file.
<action>

path= "/somerequest"

type="com.somepackage.someAction"

scope="request"

name="someForm"

validate="true"

input="somejsp.jsp"

<forward name="Success" path="/action/xys" redirect="true"/>

<forward name="Failure" path="/somejsp.jsp" redirect="true"/>
</action>
The action forward mappings also can be specified in a global section, independent of any specific action mapping.
<global-forwards>

<forward name="Success" path="/action/somejsp.jsp" />

<forward name="Failure" path="/someotherjsp.jsp" />
</global-forwards>
T
Struts Model
A model represents an application’s data and contains the logic for accessing and manipulating that data. Any data that is part of the persistent state of the application should reside in the model objects. The business objects update the application state. ActionForm bean represents the Model state at a session or request level, and not at a persistent level. Model services are accessed by the controller for either querying or effecting a change in the model state. The model notifies the view when a state change occurs in the model.The JSP file reads information from the ActionForm bean using JSP tags.

The Struts frame work doen't offer much in the way pf building model components. The Enterprise JavaBeans (EJB), Java Data Objects(JDO) and JavaBeans can be use as a model. Struts frame work doesn't limit you to one particular model implementation.
hat mak
Struts View
The view is responsible for rendering the state of the model. The presentation semantics are encapsulated within the view, therefore model data can be adapted for several different kinds of clients.The view modifies itself when a change in the model is communicated to the view. A view forwards user input to the controller.The view is simply a JSP or HTML file. There is no flow logic, no business logic, and no model information -- just tags. Tags are one of the things that make Struts unique compared to other frameworks like Velocity.

The view components typically employed in a struts application are
HTML
Data Transfer Objects
Struts ActionForms
JavaServer pages
Custom tags
Java resource bundles

Struts ActionForm
Struts ActionForm objects are used to pass client input data back and forth between the user and the business layer. The framework automatically collects the input from the request and passes this data to an Action using a form bean, which is then passed to the business layer.
e Struts unique compared to other frameworks like Velocity.
JAVA

Java is an object-oriented programming language developed by Sun Microsystems. Java language was designed to be small, simple, and portable across platforms and operating systems, both at the source and at the binary level, which means that Java programs (applets and applications) can run on any machine that has the Java virtual machine installed.

Java is Platform independent, Platform independence means, the ability of a program to move easily from one computer system to another-is one of the most significant advantages that Java has over other programming languages, particularly if your software needs to run on many different platforms.
The Java language was developed at Sun Microsystems in 1991 as part of a research project to develop software for consumer electronics devices. Java's rapidly growing popularity is due to the Web. But Java's inherent power does not come from the fact that it is a Web programming language. The talented software engineers at Sun, in bringing Java to the Web, have elegantly solved a much broader and more significant problem-how to develop network-capable windowing software that will run on almost any 32-bit computer and operating system.

A software developer writes programs in the Java language that use predefined software packages of the Java API. The developer compiles his or her programs using the Java compiler. This results in what is known as compiled bytecode. Bytecode is in a form that can be executed on the Java virtual machine, the core of the Java runtime system. You can think of the virtual machine as a microprocessor that is implemented in software and runs using the capabilities provided by your operating system and computer hardware. Since the Java virtual machine is not a real microprocessor, the Java bytecode is interpreted, rather than executed directly in the native machine instructions of the host computer.
  Java is exceptionally well suited to distributed networking applications because of its built-in networking support and the runtime system's capability to dynamically load Java bytecode across the network. Java also provides the capability to dynamically utilize new content and protocol handling software. The HotJava browser, written in Java, is an excellent example of Java's distributed networking capabilities.
The Java API provides full support of multithreaded programming. Multithreaded programs can be developed in a single, consistent manner, independent of the vagaries of the host operating system interface.
Java classes and objects directly support the object-oriented concepts of encapsulation, inheritance, messages and methods, and data hiding. Java interfaces provide support for multiple inheritance and polymorphism. The Java language retains all the benefits of object-oriented programming without the performance impacts associated with pure object languages, such as Smalltalk.
The Java API provides extensive support of windowing and graphical user interface development without the complexities associated with maintaining multiple window class libraries. Several visual programming tools have been developed for Java.
Java Virtual Machine

To execute a Java program, you run a program called a bytecode interpreter, which in turn reads the bytecodes and executes your Java program. The Java bytecode interpreter is often also called the Java virtual machine or the Java runtime.
Java bytecodes are a special set of machine instructions that are not specific to any one processor or computer system. A platform-specific bytecode interpreter executes the Java bytecodes. The bytecode interpreter is also called the Java virtual machine or the Java runtime interpreter.
The Java virtual machine, which is a component of the runtime system, is responsible for interpreting the bytecodes and making the appropriate system level calls to the native platform. It is at this point where platform independence is achieved by Java; the bytecodes are in a generic form that is only converted to a native form when processed by the virtual machine.

The JVM concept allows a layer of translation between the executable program and the machine-specific code. In a non-Java compiler, the source code is compiled into machine- specific assembly code. In doing this, the executable limits itself to the confines of that machine architecture. Compiling Java code creates an executable using JVM assembly directives. The difference of the two approaches is quite fundamental to the portability of the executable. Non-Java executables communicate directly with the platform's instruction set. Java executables communicate with the JVM instruction set, which is then translated into platform-specific instructions.
A Java Virtual Machine starts execution by invoking the method main of some specified class, passing it a single argument, which is an array of strings.
Java programs

Java can be used to create two types of programs: applets and stand-alone applications. An Applet is simply a part of a Web page, just as an image or a line of text can be. Just as a browser takes care of displaying an image referenced in an HTML document, a Java-enabled browser locates and runs an Applet . When your Java-capable Web browser loads the HTML document, the Java applet is also loaded and executed.

Java applications are standalone Java programs that do not require a Web browser to run. Java applications are more general-purpose programs such as you'd find on any computer.
A single Java program can be an applet or an application, or both, depending on how you write that program and the capabilities that program uses.
Java applets

An applet is a mini-program that will run only under a Web browser. The applet is downloaded automatically as part of a Web page. When the applet is activated it executes a program. This is part of its beauty – it provides you with a way to automatically distribute the client software from the server at the time the user needs the client software, and no sooner. They get the latest version of the client software without fail and without difficult re-installation. Because of the way
Java is designed, the programmer needs to create only a single program, and that program automatically works with all computers that have browsers with built-in Java interpreters.

Applets are Java programs that execute within the context of a Web page. They interact with the user while his Web page is active and stop their execution when his Web page is no longer active. Applets are valuable because they are simple to use. A user only needs to open an applet's Web page to download and execute an applet.

Java applets, are run from inside a browser. A reference to an applet is embedded in a Web page using a special HTML tag. When a reader, using a Java-enabled browser, loads a Web page with an applet in it, the browser downloads that applet from a Web server and executes it on the local system Because Java applets run inside a Java browser, they have access to the structure the browser provides: an existing window, an event-handling and graphics context, and the surrounding user interface.


 
One advantage a Java applet has over a scripted program is that it’s in compiled form, so the source code isn’t available to the client.
Applet security is a major concern among Web users and applet developers. From a user's perspective, an exploitable applet security flaw could result in sensitive data being modified or disclosed, or their computer being rendered inoperable. From a developer's perspective, strong applet security is necessary to make Web users comfortable with using applets. However, too high a level of security limits their applets' capabilities
Java arrays

An array is simply a sequence of either objects or primitives, all the same type and packaged together under one identifier name. Arrays are defined and used with the square-brackets indexing operator [ ]. To define an array you simply follow your type name with empty square brackets:

int[] a1;

You can also put the square brackets after the identifier to produce exactly the same meaning:

int a1[];

This conforms to expectations from C and C++ programmers. The former style, however, is probably a more sensible syntax, since it says that the type is “ an int array.”


The compiler doesn’t allow you to tell it how big the array is. This brings us back to that issue of “ handles.” All that you have at this point is a handle to an array, and there’s been no space allocated for the array. To create storage for the array you must write an initialization expression. For arrays, initialization can appear anywhere in your code, but you can also use a special kind of initialization expression that must occur at the point where the array is created. This special initialization is a set of values surrounded by curly braces. The storage allocation (the equivalent of using new) is taken care of by the compiler in this case.For example:

int[] a1 = { 1, 2, 3, 4, 5 };



Java Collection Framework

We have tried you to make a walk through the Collection Framework. The Collection Framework provides a well-designed set if interface and classes for sorting and manipulating groups of data as a single unit, a collection.
The Collection Framework provides a standard programming interface to many of the most common abstractions, without burdening the programmer with too many procedures and interfaces.
The Collection Framework is made up of a set of interfaces for working with the groups of objects. The different interfaces describe the different types of groups. For the most part, once you understand the interfaces, you understand the framework. While you always need to create specific, implementations of the interfaces, access to the actual collection should be restricted to the use of the interface methods, thus allowing you to change the underlying data structure, without altering the rest of your code.
In the Collections Framework, the interfaces Map and Collection are distinct with no lineage in the hierarchy. The typical application of map is to provide access to values stored by keys.
When designing software with the Collection Framework, it is useful to remember the following hierarchical relationship of the four basic interfaces of the framework.
  • The Collection interface is a group of objects, with duplicates allowed.
  • Set extends Collection but forbids duplicates.
  • List extends Collection also, allows duplicates and introduces positional indexing.
  • Map extends neither Set nor Collection

Interface
Implementation
Historical
Set
HashSet
TreeSet
List
ArrayList
LinkedList
Vector
Stack
Map
HashMap
Treemap
Hashtable
Properties
The historical collection classes are called such because they have been around since 1.0 release of the java class libraries. If you are moving from historical collection to the new framework classes, one of the primary differences is that all operations are synchronized with the new classes. While you can add synchronization to the new classes, you cannot remove from the old.

Explore the Interface and Classes of Java Collection Framework

Collection Interface
Iterator Interface
Set Interface
List Interface
ListIterator Interface
Map Interface
SortedSet Interface
SortedMap Interface
HashSet & TreeSet Classes

ArrayList & LinkedList Classes

1 comment:

  1. Hola peeps,


    Muchas Gracias Mi Amigo! You make learning so effortless. Anyone can follow you and I would not mind following you to the moon coz I know you are like my north star.


    I'm new to this forum. I'm working on Selenium Webdriver and have general Java question. Looking for some guidance.
    My test package in Java has multiple independent classes (Test 1,2,3 ..etc). I have a driver class (outside of that package) that should execute Test 1, then get the result to a variable in driver class, then to Test 2 & back to driver and so on. On driver class after executing each test class, I want to record whether it's successful or not.
    Please suggest different ways it cab be done
    .
    I thought about constructors, but that wouldnt return anything back from classes. I can call methods of individual classes, but that makes my driverclass look ugly when I develop rest of the classes that could be close to 50+. Also, the selection of which class (Test 1 / 2/ 3) to be run would depend on an input from user (for now, I just have Temp1, Temp2 strings, down the line I will replace them with an input from user (spreadsheet or something) that tells which class file to be run.
    Here is my driver class:





    Awesome! Thanks for putting this all in one place. Very useful!


    Cheers,
    Ajeeth Kapoor

    ReplyDelete