JAVA / JDK Version History

Java Version History

JDK 1.0 (january 23, 1996) oak
– Initial release

JDK 1.1 (february 19, 1997)
– Retooling of the AWT event model
– Inner classes added to the language
– JavaBeans
– JDBC
– RMI

J2SE 1.2 (December 8, 1998) playground
This and subsequent releases through J2SE 5.0 were rebranded retrospectively Java 2 & version name “J2SE”
(Java 2 platform, Standard edition) replaced JDK to distinguish the base platform from
J2EE (java 2 platform, enterprise edition) and J2ME (java 2 platform, micro edition).

– Strictfp keyword
– Reflection
– Swing api integration into the core classes
– JVM equipped with a jit compiler
– Java plug-in
– Java IDL
– An IDL implementation for corba interoperability
– Collections Framework

J2SE 1.3 (may 8, 2000) kestrel
– Hotspot jvm included
– JavaSound
– JNDI included in core libraries
– Java platform debugger architecture (jpda)
– RMI was modified to support optional compatibility with corba

J2SE 1.4 (february 6, 2002) merlin
– assert keyword
– Regular expressions
– Exception chaining (allows an exception to encapsulate original lower-level exception)
– Internet protocol version 6 (IPV6) support
– Non-blocking nio (new input/output)
– Logging API
– Image i/o api for reading and writing images in formats like jpeg and png
– Integrated XML parser and XSLT processor (JAXP)
– Integrated security and cryptography extensions (JCE, JSSE, JAAS)
– Java web start

J2SE 5.0 (september 30, 2004) tiger [originally numbered 1.5]
– Generics: provides compile-time (static) type safety for collections and eliminates the need for most typecasts (type conversion).
– Metadata: also called annotations; allows language constructs such as classes and methods to be tagged with additional data, which can then be processed by metadata-aware utilities.
– Autoboxing/unboxing: automatic conversions between primitive types (such as int) and primitive wrapper classes (such as integer).
– Enumerations: the enum keyword creates a typesafe, ordered list of values (such as day.monday, day.tuesday, etc.). Previously this could only be achieved by non-typesafe constant integers or manually constructed classes (typesafe enum pattern).
– Swing: new skinnable look and feel, called synth.
– Var args: the last parameter of a method can now be declared using a type name followed by three dots (e.g. Void drawtext(string… Lines)). In the calling code any number of parameters of that type can be used and they are then placed in an array to be passed to the method, or alternatively the calling code can pass an array of that type.
– Enhanced for each loop: the for loop syntax is extended with special syntax for iterating over each member of either an array or any iterable, such as the standard collection classesfix the previously broken semantics of the java memory model, which defines how threads interact through memory.
– Automatic stub generation for rmi objects.
– Static imports concurrency utilities in package java.util.concurrent.
– Scanner class for parsing data from various input streams and buffers.
– Assertions
– StringBuilder class (in java.lang package)
– Annotations

Java SE 6 (december 11, 2006) mustang
sun replaced the name “J2SE” with java se and dropped the “.0” from the version number.
Beta versions were released in february and june 2006, leading up to a final release that occurred on december 11, 2006.
The current revision is update 14 which was released in may 2009.

– Support for older win9x versions dropped.
– Scripting lang support: Generic API for integration with scripting languages, & built-in mozilla javascript rhino integration
– Dramatic performance improvements for the core platform, and swing.
– Improved web service support through JAX-WS JDBC 4.0 support
– Java compiler API: an API allowing a java program to select and invoke a java compiler programmatically.
– Upgrade of JAXB to version 2.0: including integration of a stax parser.
– Support for pluggable annotations
– Many GUI improvements, such as integration of swingworker in the API, table sorting and filtering, and true swing double-buffering (eliminating the gray-area effect).

Java se 6 update 10
A major enhancement in terms of end-user usability.
– Java Deployment Toolkit, a set of javascript functions to ease the deployment of applets and java web start applications.
– Java Kernel, a small installer including only the most commonly used jre classes. Enhanced updater.
– Enhanced versioning and pack200 support: server-side support is no longer required.
– Java quick starter, to improve cold start-up time.
– Improved performance of java2D graphics primitives on windows, using direct3D and hardware acceleration.
– A new Swing look and feel called NIMBUS and based on synth.
– Next-generation java plug-in: applets now run in a separate process and support many features of web start applications.

Java se 6 update 12
This release includes the highly anticipated 64-bit java plug-in (for 64-bit browsers only), windows server 2008 support,
and performance improvements of java and JAVAFX applications.

 

Java SE 7

  • Swing
  • IO and New IO
  • Networking
  • Security
  • Concurrency Utilities
  • Rich Internet Applications (RIA)/Deployment
    • Requesting and Customizing Applet Decoration in Dragg able Applets
    • Embedding JNLP File in Applet Tag
    • Deploying without Codebase
    • Handling Applet Initialization Status with Event Handlers
  • Java 2D
  • Java XML – JAXP, JAXB, and JAX-WS
  • Internationalization
  • java.lang Package
    • Multithreaded Custom Class Loaders in Java SE 7
  • Java Programming Language
    • Binary Literals
    • Strings in switch Statements
    • The try-with-resources Statement
    • Catching Multiple Exception Types and Rethrowing Exceptions with Improved Type Checking
    • Underscores in Numeric Literals
    • Type Inference for Generic Instance Creation
    • Improved Compiler Warnings and Errors When Using Non-Reifiable Formal Parameters with Varargs Methods
  • Java Virtual Machine (JVM)
    • Java Virtual Machine Support for Non-Java Languages
    • Garbage-First Collector
    • Java HotSpot Virtual Machine Performance Enhancements
  • JDBC

 

 

Difference Between Stack and Heap

What Is Stack?

Each Java virtual machine thread has a private Java virtual machine stack, created at the same time as the thread. A Java virtual machine stack stores frames. It holds local variables and partial results, and plays a part in method invocation and return. Because the Java virtual machine stack is never manipulated directly except to push and pop frames, frames may be heap allocated. The memory for a Java virtual machine stack does not need to be contiguous.

The Java virtual machine specification permits Java virtual machine stacks either to be of a fixed size or to dynamically expand and contract as required by the computation. If the Java virtual machine stacks are of a fixed size, the size of each Java virtual machine stack may be chosen independently when that stack is created. A Java virtual machine implementation may provide the programmer or the user control over the initial size of Java virtual machine stacks, as well as, in the case of dynamically expanding or contracting Java virtual machine stacks, control over the maximum and minimum sizes.

The following exceptional conditions are associated with Java virtual machine stacks:

  • If the computation in a thread requires a larger Java virtual machine stack than is permitted, the Java virtual machine throws a StackOverflowError.
  • If Java virtual machine stacks can be dynamically expanded, and expansion is attempted but insufficient memory can be made available to effect the expansion, or if insufficient memory can be made available to create the initial Java virtual machine stack for a new thread, the Java virtual machine throws an OutOfMemoryError

The Stack section of memory contains methods, local variables and reference variables.

What Is Heap?

The Java virtual machine has a heap that is shared among all Java virtual machine threads. The heap is the runtime data area from which memory for all class instances and arrays is allocated.

The heap is created on virtual machine start-up. Heap storage for objects is reclaimed by an automatic storage management system (known as a garbage collector); objects are never explicitly deallocated. The Java virtual machine assumes no particular type of automatic storage management system, and the storage management technique may be chosen according to the implementor’s system requirements. The heap may be of a fixed size or may be expanded as required by the computation and may be contracted if a larger heap becomes unnecessary. The memory for the heap does not need to be contiguous.

The heap mainly store objects create using or class level variables.

The following exceptional condition is associated with the heap:

  • If a computation requires more heap than can be made available by the automatic storage management system, the Java virtual machine throws an OutOfMemoryError

The Heap section contains Objects (may also contain reference variables).

Points to Remember:

  • When a method is called , a frame is created on the top of stack.
  • Once a method has completed execution , flow of control returns to the calling method and its corresponding stack frame is flushed.
  • Local variables are created in the stack
  • Instance variables are created in the heap & are part of the object they belong to.
  • Reference variables are created in the stack.

What if Object has a reference as its instance variable?


public static void main(String args[]){

A parent = new A();
//more code

}

class A{

B child = new B();
int e;
//more code

}

class B{

int c;
int d;
//more code

}

In this case , the reference variable “child” will be created in heap ,which in turn will be pointing to its object, something like the diagram shown below.

Get Nth highest record from table

Hello friends,

Recently in one interview i had question for get 3rd highest amount  record from table ,

i had make query with sub-query , but interviewer had something different in mind and told me any another option, so here i will  post some of the option to get nth highest record…

1) select * from (select year,amount,row_number() over (order by amount desc) rn from budget) where rn = 3;

2) SELECT *  FROM budget A WHERE &N = (SELECT COUNT (DISTINCT (b.amount)) FROM budget B WHERE a.amount<=b.amount);

here we have to give value N = 3

3)select amount from (select amount from (select distinct amount from ( select distinct amount from budget order by amount desc) where rownum<=3) order by amount asc) where rownum<=1;

4) select amount from (select rownum r1,amount from (select distinct(amount) from budget where amount is NOT NULL order by amount desc)) where  r1 = 3;

5) SELECT LEVEL,MAX(amount) FROM budget WHERE LEVEL IN (3) CONNECT BY PRIOR amount > amount GROUP BY LEVEL;

here, interestingly we can get 2nd and 3rd most highest amount record also…

SELECT LEVEL,MAX(amount) FROM budget WHERE LEVEL IN (2,3) CONNECT BY PRIOR amount > amount GROUP BY LEVEL;

 

I had find this much , you have to try for more option and if you will get it then please post in comments.

Cheers….  🙂

Struts 1.x Vs Struts 2.x

Struts 2.x is very simple as compared to struts 1.x, few of its excelent features are:

1. Servlet Dependency:

Actions in Struts1 have dependencies on the servlet API since the HttpServletRequest and HttpServletResponse objects are passed to the execute method when an Action is invoked but in case of Struts 2, Actions are not container dependent because they are made simple POJOs. In struts 2, the servlet contexts are represented as simple Maps which allows actions to be tested in isolation. Struts 2 Actions can access the original request and response, if required. However, other architectural elements reduce or eliminate the need to access the HttpServetRequest or HttpServletResponse directly.

2. Action classes

Programming the abstract classes instead of interfaces is one of design issues of struts1 framework that has been resolved in the struts 2 framework.
Struts1 Action classes needs to extend framework dependent abstract base class. But in case of Struts 2 Action class may or may not implement interfaces to enable optional and custom services. In case of Struts 2 , Actions are not container dependent because they are made simple POJOs. Struts 2 provides a base ActionSupport class to implement commonly used interfaces. Albeit, the Action interface is not required. Any POJO object with an execute signature can be used as an Struts 2 Action object.

3. Validation

Struts1 and Struts 2 both supports the manual validation via a validate method.
Struts1 uses validate method on the ActionForm, or validates through an extension to the Commons Validator. However, Struts 2 supports manual validation via the validate method and the XWork Validation framework. The Xwork Validation Framework supports chaining validation into sub-properties using the validations defined for the properties class type and the validation context.

4. Threading Model

In Struts1, Action resources must be thread-safe or synchronized. So Actions are singletons and thread-safe, there should only be one instance of a class to handle all requests for that Action. The singleton strategy places restrictions on what can be done with Struts1 Actions and requires extra care to develop. However in case of Struts 2, Action objects are instantiated for each request, so there are no thread-safety issues. (In practice, servlet containers generate many throw-away objects per request, and one more object does not impose a performance penalty or impact garbage collection.)

5. Testability

Testing Struts1 applications are a bit complex. A major hurdle to test Struts1 Actions is that the execute method because it exposes the Servlet API. A third-party extension, Struts TestCase, offers a set of mock object for Struts1. But the Struts 2 Actions can be tested by instantiating the Action, setting properties and invoking methods. Dependency Injection support also makes testing simpler. Actions in struts2 are simple POJOs and are framework independent, hence testability is quite easy in struts2.

6. Harvesting Input

Struts1 uses an ActionForm object to capture input. And all ActionForms needs to extend a framework dependent base class. JavaBeans cannot be used as ActionForms, so the developers have to create redundant classes to capture input.
However Struts 2 uses Action properties (as input properties independent of underlying framework) that eliminates the need for a second input object, hence reduces redundancy. Additionally in struts2, Action properties can be accessed from the web page via the taglibs. Struts 2 also supports the ActionForm pattern, as well as POJO form objects and POJO Actions. Even rich object types, including business or domain objects, can be used as input/output objects.

7. Expression Language

Struts1 integrates with JSTL, so it uses the JSTL-EL. The struts1 EL has basic object graph traversal, but relatively weak collection and indexed property support. Struts 2 can also use JSTL, however it supports a more powerful and flexible expression language called “Object Graph Notation Language” (OGNL).

8. Binding values into views

In the view section, Struts1 uses the standard JSP mechanism to bind objects (processed from the model section) into the page context to access. However Struts 2 uses a “ValueStack” technology so that the taglibs can access values without coupling your view to the object type it is rendering. The ValueStack strategy allows the reuse of views across a range of types which may have the same property name but different property types.

9. Type Conversion

Usually, Struts1 ActionForm properties are all Strings. Struts1 uses Commons-Beanutils for type conversion. These type converters are per-class and not configurable per instance. However Struts 2 uses OGNL for type conversion. The framework includes converters for basic and common object types and primitives.

10. Control Of Action Execution

Struts1 supports separate Request Processor (lifecycles) for each module, but all the Actions in a module must share the same lifecycle. However Struts 2 supports creating different lifecycles on a per Action basis via Interceptor Stacks. Custom stacks can be created and used with different Actions as needed.

Spring vs Struts 2.0

While creating J2EE applications, it needs to be decided some times which technology we should go for – Struts or Spring. This is some points comparison between Spring and Struts.

1. In most of the key features compared, Spring MVC and Struts 2 are equally good, except in the UI supports. It seems to me Spring MVC just provides tags for basic HTML form tags while Struts/WebWork 2 provides many out-of-box JSF-styled complex and composite tags, such as:
a) Struts 2 integrates with Dojo AJAX framework closely and provides many complex UI components out-of-box, such as datepicker, tooltips, etc.
b) Struts 2 has AJAX theme.
c) Struts 2 tags are stylesheet-driven, making it easier to develop consistent pages.
d) Struts 2 checkboxes are stateful, and require no special handling.
The recent release of Spring 2.0 does not seem to have any work on this area.

2. Struts is mainly a presentation layer framework, like redirecting to a particular page ,doing client side validations etc which otherwise very tedious using jsp and servlets. Spring is a complete J2EE framework having seven independent layers which can be used all together or few layers integrated with some other framework. Spring provides declarative transaction management and AOP. One layer of spring is for presentation purpose like struts but for only presentation layer, struts is better than spring.

3. Struts has been around a long time and has been popular for years – there’s a wealth of knowledge about it in the user community and more literature around

4. If you want a bunch of taglibs that generate form fields and so forth, Struts is probably the better choice.

5. Our UI is mostly click-driven and light on data and validation. It seems to me that most people run into difficulties with Struts when they start moving a lot of data from HTTP into the model. We didn?t have that problem .

6. Spring does not present a framework for implementing business/domain logic. It helps you create a Controller and a View for your application, no Model though. Spring is a fully fledged application framework, that has a large stack of sub projects.

7. As for spring, if we look at its history, it started as an effort for supplying a solution for enterprise java applications, and to replace EJBs (while it also provided integration with EJBs for people who didn’t want to ditch that). Spring is much more than an MVC framework. It provides dependency injection, AOP, integration with almost every known framework, a security framework (a separate sub-project), and a lot of other stuff. Struts 2 and hibernate integrate easily with spring, so you might like to add it to your stack, without ditching struts 2
8. If you’re going to use Spring for other middleware services, and you have no Struts expertise in house, then it would be simplest to go with SpringMVC. If you know Struts well or have team members who do, or you already have a Struts project, it may make sense to stick with it.

So, basically, it depends on the requirements and the resources what and how you want to achieve which will decide what is to be used, Stuts 2.0 or Spring.

HashMap vs Hashtable vs HashSet

I was reading about collection framework of Java. And was studying Hashtable, HashMap and HashSet. Its quite interesting to know the differences between them. In this post I will discuss these three with examples.

Hashtable

Hashtable is basically a datastructure to retain values of key-value pair.

  • It didn’t allow null for both key and value. You will get NullPointerException if you add null value.
  • It is synchronized. So it comes with its cost. Only one thread can access in one time
Hashtable<Integer,String>; cityTable = new Hashtable<Integer,String>();
cityTable.put(1, "Lahore");
cityTable.put(2, "Karachi");
cityTable.put(3, null); /* NullPointerEcxeption at runtime*/

System.out.println(cityTable.get(1));
System.out.println(cityTable.get(2));
System.out.println(cityTable.get(3));

HashMap

Like Hashtable it also accepts key value pair.

  • It allows null for both key and value
  • It is unsynchronized. So come up with better performance
HashMap<Integer,String> productMap = new HashMap<Integer,String>();
productMap.put(1, "Keys");
productMap.put(2, null);

HashSet

HashSet does not allow duplicate values. It provides add method rather put method. You also use its contain method to check whether the object is already available in HashSet. HashSet can be used where you want to maintain a unique list.

HashSet<String> stateSet = new HashSet<String>();
stateSet.add ("CA");
stateSet.add ("WI");
stateSet.add ("NY");

if (stateSet.contains("PB")) /* if CA, it will not add but shows following message*/
System.out.println("Already found");
else
stateSet.add("PB");

Vector or ArrayList — which is better?

 Vector or ArrayList — which is better and why?

Sometimes Vector is better; sometimes ArrayListis better; sometimes you don’t want to use either. I hope you weren’t looking for an easy answer because the answer depends upon what you are doing. There are four factors to consider:

  • API
  • Synchronization
  • Data growth
  • Usage patterns

Let’s explore each in turn.

API

In The Java Programming Language (Addison-Wesley, June 2000) Ken Arnold, James Gosling, and David Holmes describe the Vector as an analog to the ArrayList. So, from an API perspective, the two classes are very similar. However, there are still some major differences between the two classes.

Synchronization

Vectors are synchronized. Any method that touches the Vector‘s contents is thread safe. ArrayList, on the other hand, is unsynchronized, making them, therefore, not thread safe. With that difference in mind, using synchronization will incur a performance hit. So if you don’t need a thread-safe collection, use the ArrayList. Why pay the price of synchronization unnecessarily?

Data growth

Internally, both the ArrayList and Vector hold onto their contents using an Array. You need to keep this fact in mind while using either in your programs. When you insert an element into an ArrayList or a Vector, the object will need to expand its internal array if it runs out of room. A Vector defaults to doubling the size of its array, while the ArrayList increases its array size by 50 percent. Depending on how you use these classes, you could end up taking a large performance hit while adding new elements. It’s always best to set the object’s initial capacity to the largest capacity that your program will need. By carefully setting the capacity, you can avoid paying the penalty needed to resize the internal array later. If you don’t know how much data you’ll have, but you do know the rate at which it grows, Vector does possess a slight advantage since you can set the increment value.

Usage patterns

Both the ArrayList and Vector are good for retrieving elements from a specific position in the container or for adding and removing elements from the end of the container. All of these operations can be performed in constant time — O(1). However, adding and removing elements from any other position proves more expensive — linear to be exact: O(n-i), where n is the number of elements and i is the index of the element added or removed. These operations are more expensive because you have to shift all elements at index i and higher over by one element. So what does this all mean?

It means that if you want to index elements or add and remove elements at the end of the array, use either a Vector or an ArrayList. If you want to do anything else to the contents, go find yourself another container class. For example, the LinkedList can add or remove an element at any position in constant time — O(1). However, indexing an element is a bit slower — O(i) where i is the index of the element. Traversing an ArrayList is also easier since you can simply use an index instead of having to create an iterator. The LinkedList also creates an internal object for each element inserted. So you have to be aware of the extra garbage being created.

Finally, in “PRAXIS 41” from Practical Java (Addison-Wesley, Feb. 2000) Peter Haggar suggests that you use a plain old array in place of either Vector or ArrayList — especially for performance-critical code. By using an array you can avoid synchronization, extra method calls, and suboptimal resizing. You just pay the cost of extra development time.

Java Server Pages (JSP) Interview Questions

Question 1: Which of the following is not a standard method called as part of the JSP life cycle?

Answer: jspService()

 

Question 2: If you want to override a JSP file’s initialization method, within what type of tags must you declare the method?

Answer: <%! %>

 

Question 3: Which can not be used as the scope when using a JavaBean with JSP?

Answer:  Response is not a valid object scope for JavaBeans

 

Question 4: Why use RequestDispatcher to forward a request to another resource, instead of using a sendRedirect

Answer: The RequestDispatcher does not require a round trip to the client, and thus is more efficient and allows the server to maintain request state.

 

Question 5: What is the key difference between using a <jsp:forward> and HttpServletResponse.sendRedirect()?

Answer: forward executes on the server while sendRedirect() executes on the client.

 

Question 6: How you  makes your compiled JSP page implement the SingleThreadModel interface?

Answer: <%@ page isThreadSafe=”false” %>

 

Question 7: What is the difference between doing an include or a forward with a RequestDispatcher?

 Answer: When the forward method is used, the invoking resource does not regain control. Multiple include invocations can be made from the same resource, while the invoking resource maintains execution control.

 

Question 8: When a JSP page is compiled, what is it turned into?

Answer: Servlet

 

Question 9: What is JavaServer Pages technology?

Answer: JavaServer Pages (JSP) technology provides a simplified, fast way to create web pages that display dynamically generated content. The JSP specification, developed through an industry-wide initiative led by Sun Microsystems, defines the interaction between the server and the JSP page, and describes the format and syntax of the page.

 

Question 10: How does the JavaServer Pages technology work?

Answer: JSP pages use XML tags and scriptlets written in the JavaTM programming language to encapsulate the logic that generates the content for the page. It passes any formatting (HTML or XML) tags directly back to the response page. In this way, JSP pages separate the page logic from its design and display.

 

JSP technology is part of the Java technology family; it uses a Java programming language-based scripting language, and JSP pages are compiled into servlets. JSP pages may call JavaBeansTM components (beans) or Enterprise JavaBeansTM components (enterprise beans) to perform processing on the server. As such, JSP technology is a key component in a highly scalable architecture for web-based applications.

 

JSP pages are not restricted to any specific platform or web server. The JSP specification represents a broad spectrum of industry input.

 

Question 11: Why do I need JSP technology if I already have servlets?

Answer: JSP pages are compiled into servlets, so theoretically you could write servlets to support your web-based applications. However, JSP technology was designed to simplify the process of creating pages by separating web presentation from web content. In many applications, the response sent to the client is a combination of template data and dynamically-generated data. In this situation, it is much easier to work with JSP pages than to do everything with servlets.

 

Question 12: What is a JSP page?

Answer: A JSP page is a page created by the web developer that includes JSP technology-specific tags, declarations, and possibly scriptlets, in combination with other static (HTML or XML) tags. A JSP page has the extension .jsp; this signals to the web server that the JSP engine will process elements on this page.

 

Question 13: How do JSP pages work?

Answer: A JSP engine interprets tags and scriptlets, and generates the content required – for example, by calling a bean, accessing a database with the JDBCTM API or including a file. It then sends the results back in the form of an HTML (or XML) page to the browser. The logic that generates the content is encapsulated in tags and beans processed on the server. JSP scriptlets let developers tie everything together, and ordinary HTML tags control the formatting and display of the generated page.

 

Question 14: How is a JSP page invoked and compiled?

Answer: Pages built using JSP technology are typically implemented using a translation phase that is performed once, the first time the page is called. The page is compiled into a Java Servlet class and remains in server memory, so subsequent calls to the page have very fast response times.

 

Question 15: Can I create XML pages using JSP technology?

Answer: Yes, the JSP specification does support creation of XML documents. For simple XML generation, the XML tags may be included as static template portions of the JSP page. Dynamic generation of XML tags occurs through bean components or custom tags that generate XML output. See the white paper Developing XML Solutions with JavaServer Pages Technology (PDF) for details.

 

Question 16: Can I generate and manipulate JSP pages using XML tools?

Answer: The JSP 1.1 specification describes a mapping between JSP pages and XML documents.The mapping enables the creation and manipulation of JSP pages using XML tools.

 

Question 17: How do I use JavaBeans components (beans) from a JSP page?

Answer: The JSP specification includes standard tags for bean use and manipulation. The useBean tag creates an instance of a specific JavaBeans class. If the instance already exists, it is retrieved. Otherwise, it is created. The setProperty and getProperty tags let you manipulate properties of the given object. These tags are described in more detail in the JSP specification and tutorial.

 

Question 18: Why are there no try/catch blocks around my JSP scriptlets? I know the code should throw errors.

Answer: Don’t be confused. Scriplets do eventually end up with try/catch blocks around thier code. A JSP will catch any thrown error and display it to a user, or optionally handle it with a error page if specified.

 

If you would like to see the error handling examine the generated code by your JSP container.

 

Question 19: How do I call a function in my JSP via client-side JavaScript?

Answer: It is not possible to do that.

 

A common misconception about JSP is where it takes place. JSP occurs only on the server-side. As it implies, client-side JavaScript takes place only on the client’s computer. You cannont interchange the two.

 

Question 20: What are Implicit Objects?

Answer. An implicit object is available for a JSP developer to use inside scriptlets and expressions. The implicit objects represent all of the important components of the PageContext. Implicit objects need not be declared. They already exist and an error will be thrown if another variable of the same name is used.

 

User friendly documentaion of the implicit objects along with code examples is also provided at JSP Insider. Here is a list of the JSP 1.1 implicit objects and links for the documentation provided by JSP Insider.

 

A. pageContext

B. application

C. out

D. response

E. request

F: Session

 

Question 21: Is it possible to pass in any Object other than a String to a taglib?

Answer. Yes, just use an expression. The value of the expression will not be converted to a string in this case.

Take the following example

<example:tag date=”<%= new java.util.Date()%>” />

In the above example, the corresponding tag handler will have the setDate method called with a java.util.Date object passed in as a parameter.

This is perfectly valid in your JSP assuming the tag’s value can be a runtime expression. The TLD for this taglibrary would have to include the following snippet.

<attribute>

<name>date</name>

<rtexprvalue>true</rtexprvalue>

</attribute>

Question 22: Both <%!…%> and <%…%> can be used for declaring variables. What is the difference between both and which to use?

Answer: There is a distinct difference between an declaration, <%!…%>, and a scriptlet, <%…%>.

 

<%!…%> Declares a variable or method valid in the scripting language used in the JSP page.

<%…%> Contains a code fragment valid in the pages scripting language.

 

The big difference is that <%…%> is initialized once per each request to the JSP. Often the <%…%> is prefered and recommended for this reason, variables declared by <%!…%> are only loaded once, at the beginning of the JSP’s lifecycle.

Question 23: What JSP servers are currently available?

Answer: Here’s a list of JSP servers with which we are familiar. This is only a partial list.

Extreme Internet Server

IPlanet WebServer

JRun

Orion

Resin

Tomcat

WebLogic

WebSphere

ServletExec

LiteWebServer

For a more complete list check out the Java server list at the Java Skyline web site. This list contains more than just JSP servers, but it is a great place to start.

Question 24: How do I Pass an Object between a Servlet and a JSP?

Answer: On the server-side you may forward the request with, pageContext.forward(“Relative URI…”); for a JSP, or with getServletConfig().getServletContext().getRequestDispatcher(“Relative URI…”).forward(request, response); for a Servlet. The same HttpServletRequest object is shared when using these methods. Because of this objects may be stashed and retrieved using the getAttribute() and setAttribute() methods of HttpServletRequest.

 

Take for example the following Servlet. A java.lang.String object is set in the request object with “text” as the key. The servlet then fowards to a JSP.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class ExampleServlet extends HttpServlet 
{
  public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException   
  {
   String text  = new String("Some text to pass...");
   request.setAttribute("text", text);
   getServletConfig().getServletContext().getRequestDispatcher("/test.jsp").forward(request, response);

  }
}

 

Using getAttribute(), a JSP can access the object set by the servlet.

 

1
2
3
4
5
6
7
8
9
10
<html>
 <head><title>Passing an object.</title></head>
 <body>
<%
  String text = (String)request.getAttribute("text");
%>
<%= text %>
 </body>
</html>

 

If the result would be a webpage displaying, “Some text to pass…”

 

Any object may be passed using this method. Just remember to use the appropriate type cast when getting the object from the request. This method may also be used to pass objects between only servlets or JSP.

 

Question 25: How can I set a cookie in JSP?

Answer: This should work:

 

response.setHeader(“Set-Cookie”, “cookie string”);

To give the response-object to a bean, write a method setResponse

(HttpServletResponse response)

– to the bean, and in jsp-file:

 

<%

bean.setResponse (response);

%>

 

Question 26: How can I include one JSP inside another JSP?

Answer: <%@ include=”FileName.jsp” %>

Question 27: How do I delete a cookie with JSP?

Answer:

<%

Cookie killCookie = new Cookie(“foo”, null);

killCookie.setPath(“/”);

killCookie.setMaxAge(0);

response.addCookie(killCookie);

%>

 

Question 28: What is a web application?

Answer: A web application is a collection of resources that is mapped to a specific Uniform Resource Identifier (URI) prefix. These resources may include JSP pages, Servlets, HTML files, and images.

 

Question 29: If you want to override a JSP file’s initialization method, within what type of tags must you declare the method?

Answer: <%! %>

 

Question 30: Why use RequestDispatcher to forward a request to another resource, instead of using a sendRedirect?

Answer: The RequestDispatcher does not require a round trip to the client, and thus is more efficient and allows the server to maintain request state.

 

Question 31: What is the key difference between using a <jsp:forward> and HttpServletResponse.sendRedirect()?

Answer: forward executes on the server while sendRedirect() executes on the client.

 

Question 32. What is the difference between doing an include or a forward with a RequestDispatcher?

Answer: When the forward method is used, the invoking resource does not regain control. Multiple include invocations can be made from the same resource, while the invoking resource maintains execution control.

 

Question 33. What are the elements available in JSP?

Answer: There are three types of elements: directive elements, scripting elements, and action elements.

 

Question 34. How do you invoke a JSP page from a servlet?

Answer:

ServletContext context = getServletConfig().getServletContext();

context.getResourceDispatcher(urlpath).forward(request, response);

(Or)

RequestDispatcher rd = request.getRequestDispatcher(urlpath);

rd.forward(request, response);

 

Question 35. Can JSP and Servlet share same Session and Beans?

Answer: Yes

 

Question 36. What are the different scopes available for usebean tag in JSP?

Answer: Page, Request, Session and Application.

 

 

 

 

 

How HashMap works in Java?

How HashMap works in Java or sometime how get method work in HashMap is common interview questions now days. Almost everybody who worked in Java knows what hashMap is, where to use hashMap or difference between hashtable and HashMap then why this interview question becomes so special? Because of the breadth and depth this question offers. It has become very popular java interview question in almost any senior or mid-senior level java interviews.

Questions start with simple statement

“Have you used HashMap before” or “What is HashMap? Why do we use it “
Almost everybody answers this with yes and then interviewee keep talking about common facts about hashMap like hashMap accpt null while hashtable doesn’t, HashMap is not synchronized, hashMap is fast and so on along with basics like its stores key and value pairs etc.
This shows that person has used hashMap and quite familier with the funtionalities HashMap offers but interview takes a sharp turn from here and next set of follow up questions gets more detailed about fundamentals involved in hashmap. Interview here you and come back with questions like

“Do you Know how hashMap works in Java” or
“How does get () method of HashMap works in Java”
And then you get answers like I don’t bother its standard Java API, you better look code on java; I can find it out in Google at any time etc.
But some interviewee definitely answer this and will say “HashMap works on principle of hashing, we have put () and get () method for storing and retrieving data from hashMap. When we pass an object to put () method to store it on hashMap, hashMap implementation calls
hashcode() method hashMap key object and by applying that hashcode on its own hashing funtion it identifies a bucket location for storing value object , important part here is HashMap stores both key+value in bucket which is essential to understand the retrieving logic. if people fails to recognize this and say it only stores Value in the bucket they will fail to explain the retrieving logic of any object stored in HashMap . This answer is very much acceptable and does make sense that interviewee has fair bit of knowledge how hashing works and how HashMap works in Java.
But this is just start of story and going forward when depth increases a little bit and when you put interviewee on scenarios every java developers faced day by day basis. So next question would be more likely about collision detection and collision resolution in Java HashMap e.g

“What will happen if two different objects have same hashcode?”
Now from here confusion starts some time interviewer will say that since Hashcode is equal objects are equal and HashMap will throw exception or not store it again etc. then you might want to remind them aobut equals and hashCode() contract that two unequal object in Java very much can have equal hashcode. Some will give up at this point and some will move ahead and say “Since hashcode () is same, bucket location would be same and collision occurs in hashMap, Since HashMap use a linked list to store in bucket, value object will be stored in next node of linked list.” great this answer make sense to me though there could be some other collision resolution methods available this is simplest and HashMap does follow this.
But story does not end here and final questions interviewer ask like

“How will you retreive if two different objects have same hashcode?”
Hmmmmmmmmmmmmm
Interviewee will say we will call get() method and then HashMap uses keys hashcode to find out bucket location and retreives object but then you need to remind him that there are two objects are stored in same bucket , so they will say about traversal in linked list until we find the value object , then you ask how do you identify vlaue object because you don’t value object to compare ,So until they know that HashMap stores both Key and Value in linked list node they won’t be able to resolve this issue and will try and fail.

But those bunch of people who remember this key information will say that after finding bucket location , we will call keys.equals() method to identify correct node in linked list and return associated value object for that key in Java HashMap. Perfect this is the correct answer.

In many cases interviewee fails at this stage because they get confused between hashcode () and equals () and keys and values object in hashMap which is pretty obvious because they are dealing with the hashcode () in all previous questions and equals () come in picture only in case of retrieving value object from HashMap.
Some good developer point out here that using immutable, final object with proper equals () and hashcode () implementation would act as perfect Java HashMap keys and improve performance of Java hashMap by reducing collision. Immutablity also allows caching there hashcode of different keys which makes overall retreival process very fast and suggest that String and various wrapper classes e.g Integer provided by Java Collection API are very good HashMap keys.

Now if you clear all this java hashmap interview question you will be surprised by this very interesting question “What happens On HashMap in Java if the size of the Hashmap exceeds a given threshold defined by load factor ?”. Until you know how hashmap works exactly you won’t be able to answer this question.
if the size of the map exceeds a given threshold defined by load-factor e.g. if load factor is .75 it will act to re-size the map once it filled 75%. Java Hashmap does that by creating another new bucket array of size twice of previous size of hashmap, and then start putting every old element into that new bucket array and this process is called rehashing because it also applies hash function to find new bucket location.

If you manage to answer this question on hashmap in java you will be greeted by “do you see any problem with resizing of hashmap in Java” , you might not be able to pick the context and then he will try to give you hint about multiple thread accessing the java hashmap and potentially looking for race condition on HashMap in Java.

So the answer is Yes there is potential race condition exists while resizing hashmap in Java, if two thread at the same time found that now Java Hashmap needs resizing and they both try to resizing. on the process of resizing of hashmap in Java , the element in bucket which is stored in linked list get reversed in order during there migration to new bucket because java hashmap doesn’t append the new element at tail instead it append new element at head to avoid tail traversing. if race condition happens then you will end up with an infinite loop. though this point you can potentially argue that what the hell makes you think to use HashMap in multi-threaded environment to interviewer 🙂

I like this question because of its depth and number of concept it touches indirectly, if you look at questions asked during interview this HashMap questions has verified
Concept of hashing
Collision resolution in HashMap
Use of equals () and hashCode () method and there importance?
Benefit of immutable object?
race condition on hashmap in Java
Resizing of Java HashMap

Just to summararize here are the answers which does makes sense for above questions

How HashMAp works in Java
HashMap works on principle of hashing, we have put () and get () method for storing and retrieving object form hashMap.When we pass an both key and value to put() method to store on HashMap, it uses key object hashcode() method to calculate hashcode and they by applying hashing on that hashcode it identifies bucket location for storing value object.
While retrieving it uses key object equals method to find out correct key value pair and return value object associated with that key. HashMap uses linked list in case of collision and object will be stored in next node of linked list.
Also hashMap stores both key+value tuple in every node of linked list.

What will happen if two different HashMap key objects have same hashcode?
They will be stored in same bucket but no next node of linked list. And keys equals () method will be used to identify correct key value pair in HashMap.

In terms of usage HashMap is very versatile and I have mostly used hashMap as cache in electronic trading application I have worked . Since finance domain used Java heavily and due to performance reason we need caching a lot HashMap comes as very handy there.

Source : javarevisited

How Synchronization works in Java ? Example of synchronized block

In this Java synchronization tutorial we will see what is meaning of Synchronization in Java, Why do we need Synchronization in java, what is java synchronized keyword, example of using java synchronized method and blocks and important points about synchronization in Java.

Example of Synchronization in Java using synchronized method and block

Synchronization in Java is an important concept since Java is a multi-threaded language where multiple threads run in parallel to complete program execution. In multi-threaded environment synchronization of java object or synchronization of java class becomes extremely important. Synchronization in Java is possible by using java keyword “synchronized” and “volatile”. Concurrent access of shared objects in Java introduces to kind of errors: thread interference and memory consistency errors and to avoid these errors you need to properly synchronize your java object to allow mutual exclusive access of critical section to two threads.

This Java Synchronization tutorial is in continuation of my article How HashMap works in Java  and difference between HashMap and Hashtable in Java  if you haven’t read already you may find some useful information based on my experience in Java Collections.

Why do we need Synchronization in Java?

If your code is executing in multi-threaded environment you need synchronization for objects which are shared among multiple threads to avoid any corruption of state or any kind of unexpected behavior. Synchronization in Java will only be needed if shared object is mutable. if your shared object is read only or immutable object you don’t need synchronization despite running multiple threads. Same is true with what threads are doing with object if all the threads are only reading value then you don’t require synchronization in java. JVM guarantees that Java synchronized code will only be executed by one thread at a time.In Summary Java Synchronized Keyword provides following functionality essential for concurrent programming :

1) synchronized keyword in java provides locking which ensures mutual exclusive access of shared resource and prevent data race.

2) synchronized keyword also prevent reordering of code statement by compiler which can cause subtle concurrent issue if we don’t use synchronized or volatile keyword.
3) synchronized keyword involve locking and unlocking. before entering into synchronized method or block thread needs to acquire the lock at this point it reads data from main memory than cache and when it release the lock it flushes write operation into main memory which eliminates memory inconsistency errors.

Synchronized keyword in Java

Prior to Java5 synchronized keyword in java was only way to provide synchronization of shared object. Any code written in synchronized block in java will be mutual exclusive and can only be executed by one thread at a time. You can have both static synchronized method and non static synchronized method and synchronized blocks in java but we can not have synchronized variable in java. Using synchronized keyword with variable is illegal and will result in compilation error. Instead of java synchronized variable you can have java volatile variable, which will instruct JVM threads to read value of volatile variable from main memory and don’t cache it locally. Block synchronization in java is preferred over method synchronization in java because by using block synchronization you only need to lock the critical section of code instead of whole method. Since java synchronization comes with cost of performance we need to synchronize only part of code which absolutely needs to be synchronized.

Example of synchronized method in Java

Using synchronized keyword along with method is easy just apply synchronized keyword in front of method. What we need to take care is that static synchronized method locked on class object lock and non static synchronized method locks on current object (this). So it’s possible that both static and non static java synchronized method running in parallel.  This is the common mistake a naive developer do while writing java synchronized code.
public class Counter{
private static count = 0;
public static synchronized  getCount(){
  return this.count;
}
public synchoronized setCount(int count){
   this.count = count;
}
}
In this example of java synchronization code is not properly synchronized because both getCount() and setCount() are not getting locked on same object and can run in parallel which results in getting incorrect count. Here getCount() will lock in Counter.class object while setCount() will lock on current object (this). To make this code properly synchronized in java you need to either make both method static or non static or use java synchronized block instead of java synchronized method.

Example of synchronized block in Java

Using synchronized block in java is also similar to using synchronized keyword in methods. Only important thing to note here is that if object used to lock synchronized block of code, Singleton.class in below example is null then java synchronized block will throw a NullPointerException.
public class Singleton{
private static volatile Singleton _instance;
public static Singleton getInstance(){
   if(_instance == null){
            synchronized(Singleton.class){
              if(_instance == null)
              _instance = new Singleton();
            }
   }
   return _instance;
}
This is a classic example of double checked locking in Singleton. In this example of java synchronized code we have made only critical section (part of code which is creating instance of singleton) synchronized and saved some performance because if you make whole method synchronized every call of this method will be blocked while you only need to create instance on first call. To read more about Singleton in Java see here.

Important points of synchronized keyword in Java

1. Synchronized keyword in Javais used to provide mutual exclusive access of a shared resource with multiple threads in Java. Synchronization in java guarantees that no two threads can execute a synchronized method which requires same lock simultaneously or concurrently.

2. You can use java synchronized keyword only on synchronized method or synchronized block.
3. When ever a thread enters into java synchronized method or block it acquires a lock and whenever it leaves java synchronized method or block it releases the lock. Lock is released even if thread leaves synchronized method after completion or due to any Error or Exception.
4. Java Thread acquires an object level lock when it enters into an instance synchronized java method and acquires a class level lock when it enters into static synchronized java method.
5.java synchronized keyword is re-entrant in nature it means if a java synchronized method calls another synchronized method which requires same lock then current thread which is holding lock can enter into that method without acquiring lock.
6. Java Synchronization will throw NullPointerException if object used in java synchronized block is null e.g. synchronized (myInstance) will throws NullPointerException if myInstance is null.
7. One Major disadvantage of java synchronized keyword is that it doesn’t allow concurrent read which you can implement using java.util.concurrent.locks.ReentrantLock.
8. One limitation of java synchronized keyword is that it can only be used to control access of shared object within the same JVM. If you have more than one JVM and need to synchronized access to a shared file system or database, the java synchronized keyword is not at all sufficient. You need to implement a kind of global lock for that.
9. Java synchronized keyword incurs performance cost. Synchronized method in Java is very slow and can degrade performance. So use synchronization in java when it absolutely requires and consider using java synchronized block for synchronizing critical section only.
10. Java synchronized block is better than java synchronized method in java because by using synchronized block you can only lock critical section of code and avoid locking whole method which can possibly degrade performance. A good example of java synchronization around this concept is getInstance() method Singleton class. See here.
11. Its possible that both static synchronized and non static synchronized method can run simultaneously or concurrently because they lock on different object.
12. From java 5 after change in Java memory model reads and writes are atomic for all variables declared using volatile keyword (including long and double variables) and simple atomic variable access is more efficient instead of accessing these variables via synchronized java code. But it requires more care and attention from the programmer to avoid memory consistency errors.
13. Java synchronized code could result in deadlock or starvation while accessing by multiple thread if synchronization is not implemented correctly. To know how to avoid deadlock in java see here.
14. According to the Java language specification you can not use java synchronized keyword with constructor it’s illegal and result in compilation error. So you can not synchronized constructor in Java which seems logical because other threads cannot see the object being created until the thread creating it has finished it.
15. You cannot apply java synchronized keyword with variables and can not use java volatile keyword with method.
16. Java.util.concurrent.locks extends capability provided by java synchronized keyword for writing more sophisticated programs since they offer more capabilities e.g. Reentrancy and interruptible locks.
17. java synchronized keyword also synchronizes memory. In fact java synchronized synchronizes the whole of thread memory with main memory.

18. Important method related to synchronization in Java are wait(), notify() and notifyAll() which is defined in Object class.

19. Do not synchronize on non final field on synchronized block in Java. because reference of non final field may change any time and then different thread might synchronizing on different objects i.e. no synchronization at all. example of synchronizing on non final field :

private String lock = new String(“lock”);
synchronized(lock){
System.out.println(“locking on :”  + lock);

}
any if you write synchronized code like above in java you may get warning “Synchronization on non-final field”  in IDE like Netbeans and InteliJ

20. Its not recommended to use String object as lock in java synchronized block because string is immutable object and literal string and interned string gets stored in String pool. so by any chance if any other part of code or any third party library used same String as there lock then they both will be locked on same object despite being completely unrelated which could result in unexpected behavior and bad performance. instead of String object its advised to use new Object() for Synchronization in Java on synchronized block.

private static final String LOCK = “lock”;   //not recommended
private static final Object OBJ_LOCK = new Object(); //better

public void process() {
synchronized(LOCK) {
……..
}
}

21. From Java library Calendar and SimpleDateFormat classes are not thread-safe and requires external synchronization in Java to be used in multi-threaded environment.

Source : javarevisited