Saturday, September 27, 2014

Some Important Facts About Core Java

  1. There are 4 important OOPS concepts in Java : Inheritance, Abstraction, Encapsulation and Polymorphism.
  2. There are two types of variables in Java : Primitive types and Object Types
  3. The default value of Boolean is false (the same applies for the Wrapper class too).
  4. Marker interface is the one which doesn't contains any methods, it is like empty interface.
  5. You cannot override the 'main' method of the Java, even-though if you try to do so it will not give any exception, program compiles and executes fine. The reason is : 'main' method is of type static. Static methods are class level methods. Even-though it looks like method overriding, it is not overriding. These are two different method with respect to the corresponding class.
  6. You can Overload the 'main' method of Java, it is valid in Java.
  7. You can have only one 'Public' class and any number of non-public classes in any java source file.
  8. Inheritance is an example for IS-A relationship.
  9. Composition is an example for HAS-A relationship.
  10. You can have abstract class without any abstract methods.
  11. The use of abstract class without any abstract method : a) Whenever you  don't want to direct instantiation of the class, b) Whenever you want to add abstract future at later point of time which you are not aware currently, Otherwise I don't see any usage of such class.
  12. String class is immutable and thread-safe. The reason is , whenever we create String object mentioning some string literal either inside the constructor or direct literal, first it checks in the String constant pool whether that string literal is available or not. If available then it will not create the new instance inside the constant pool instead it points reference to the same string constant. In this case this string might be referenced by many different reference variables. Suppose you make changes to this string value it will alter all the referenced string variables by breaking the actual behavior. Because of this reason String class implemented as Final & Immutable one.
  13. If you want to update your string frequently and dynamically, in case you need to modify your string based on some scenario then you can either go With StringBuffer or StringBuilder based on either for Multithreaded application or Single threaded application. StringBuffer and StringBuilder both classes are same in behavior and functionality except the fact that, StringBuffer class is Synchronized and StringBuilder class non-synchronized.
  14. The efficient way of creating String object is : String str="abcd";, the reason is it creates instance only String Constant Pool and refer it through the reference variable 'str'. On other case, whenever you create String object using 'new' operator as : String str=new String("abcd");, in this case instance will be created in the heap and as well as in the String constant pool if the same string doesn't exist already, else it refers the existing string instance from the pool.

Still There are many to add, I will be updating this post in coming days....

Thursday, September 25, 2014

Rules for Overloading the Method in Java

  1. You can overload a method by changing its signature. method signature is made of number of arguments, type of arguments and order of arguments.
  2. Return type is not a part of method signature, so changing method return type means no overloading unless you change argument with return type.
  3. A method can be overloaded in the same class or in a subclass. if class A defines a display(float i) method, the subclass B could define a display(String s) method without overriding the super-class version that takes an int. So two methods with the same name but in different classes can still be considered overloaded, if the subclass inherits one version of the method and then declares another overloaded version in its class definition.

Rules for Overriding the Method in Java

  1. The argument list must exactly same that of the overridden method. If they don't match, you can end up with an overloaded method.
  2. The return type must be the same as, or a sub-type of, the return type declared in the original overridden method in the super-class (also called co-variant return type).
  3. Instance methods can be overridden only if they are inherited by the subclass.
  4. A subclass within the same package as the instance's super-class can override any super-class method that is not marked private or final. A subclass in a different package can override only those non-final methods marked public or protected (since protected methods are inherited by the subclass).
  5. The overriding method can throw any unchecked (run-time) exception, regardless of whether the overridden method declares the exception.
  6. The overriding method must not throw checked exceptions that are new or broader than those declared by the overridden method. For example, a method that declares a FileNotFoundException cannot be overridden by a method that declares a SQLException, Exception, or any other non-run-time exception unless it's a subclass of FileNotFoundException.
  7. You cannot override a method marked final.
  8. You cannot override a method marked static.
  9. If a class is not inherited, you cannot override its methods.

Wednesday, September 24, 2014

How To Increase PermGenSpace Of Eclipse ?

If you see java.lang.OutOfMemoryError: PermGen space errors, you need to increase the permanent generation space available to Eclipse.
PermGen is the permanent generation of objects in the VM (Class names, internalized strings, objects that will never get garbage-collected). An easy, if somewhat memory-hungry fix is to enlarge the maximum space for these objects by adding,

“-XX:MaxPermSize=128M”

as an argument to the JVM when starting Eclipse. The recommended way to do this is via your eclipse.ini file.
Alternatively, you can invoke the Eclipse executable with command-line arguments directly, as in

“eclipse [normal arguments] -vmargs -XX:PermSize=64M -XX:MaxPermSize=128M [more VM args]”

Note: The arguments after -vmargs are directly passed to the VM. Run java -X for the list of options your VM accepts. Options starting with -X are implementation-specific and may not be applicable to all JVMs (although they do work with the Sun/Oracle JVMs).

Eclipse and Sun VMs on Windows


Eclipse 3.3 and above supports an argument to the launcher: --launcher.XXMaxPermSize. On Windows, Eclipse ships with the following lines in the eclipse.ini file:
    
          “--launcher.XXMaxPermSize=256m”

With the above arguments, if the VM being used is a Sun VM and there is not already a -XX:MaxPermSize= VM argument, then the launcher will automatically add -XX:MaxPermSize=256m to the list of VM arguments being used. The Eclipse launcher is only capable of identifying Sun VMs on Windows.
The option --launcher.XXMaxPermSize is something that the launcher reads (not the JVM); it tells the launcher to automatically size the JVM's perm gen if it (the launcher) detects a Sun JVM that supports that option. This alleviates the need to put it under -vmargs (where non-Sun JVM's could fail because they don't understand that option).

Note: Eclipse 3.6 and below on Windows has a bug with Oracle/Sun JDK 1.6.0_21 (July 2010) where the launcher cannot detect an Oracle/Sun VM, and therefore does not use the correct PermGen size. If you are using either of this version, add the -XX flag to the eclipse.ini as described above.

Note: Eclipse 3.3.1 has a bug where the launcher cannot detect a Sun VM, and therefore does not use the correct PermGen size. It seems this may have been a known bug on Mac OS X for 3.3.0 as well. If you are using either of these platform combinations, add the -XX flag to the eclipse.ini as described above.

Sorting the list of objects in Java

This article will explain about sorting the collection of objects. The document will explain how to sort list or set of objects placed in a collection and also what are the pre-requisites to sort any list or set which is having the list of objects.

You can sort List collections using the java.util.Collections.sort() method. You can sort these two types of List's.

1.   List
2.   LinkedList

Sorting Objects by their Natural Order


To sort a List you do this:


List list = new ArrayList();
//add elements to the list
Collections.sort(list);

When sorting a list like this the elements are ordered according to their "natural order". For objects to have a natural order they must implement the interface java.lang.Comparable. In other words, the objects must be comparable to determine their order. Here is how the Comparable interface looks:

public interface Comparable<T> {
  int compareTo(T o);
}

The compareTo() method should compare this object to another object, return an int value. Here are the rules for that int value:


  • Return a negative value if this object is smaller than the other object
  • Return 0 (zero) if this object is equal to the other object.
  • Return a positive value if this object is larger than the other object.

There are a few more specific rules to obey in the implementation, but the above is the primary requirements. Check out the JavaDoc for the details.

Let's say you are sorting a List of String elements. To sort them, each string is compared to the others according to some sorting algorithm (not interesting here). Each string compares itself to another string by alphabetic comparison. So, if a string is less than another string by alphabetic comparison it will return a negative number from the compareTo() method.

When you implement the compareTo() method in your own classes you will have to decide how these objects should be compared to each other. For instance, Employee objects can be compared by their first name, last name, salary, start year or whatever else you think makes sense.

Sorting Objects Using a Comparator

Sometimes you may want to sort a list according to another order than their natural order. Perhaps the objects you are sorting do not even have a natural order. In that case you can use a Comparator instead. Here is how you sort a list using a Comparator:

List list = new ArrayList();
//add elements to the list
Comparator comparator = new SomeComparator();
Collections.sort(list, comparator);

Notice how the Collections.sort() method now takes a java.util.Comparator as parameter in addition to the List. This Comparator compares the elements in the list two by two. Here is how the Comparator interface looks:

public interface Comparator<T> {
    int compare(T object1, T object2);
}

The compare() method compares two objects to each other and should:
  • Return a negative value if object1 is smaller than object2
  • Return 0 (zero) if objec1 is equal to object2.
  • Return a positive value if object1 is larger than object2.

There are a few more requirements to the implementation of the compare() method, but these are the primary requirements. Check out the JavaDoc for more specific details.

Here is an example Comparator that compares two fictive Employee objects:


public class MyComparator<Employee> implements Comparator<Employee> {
    public int compare(Employee emp1, Employee emp2){
       if(emp1.getSalary() <  emp2.getSalary()) return -1;
       if(emp1.getSalary() == emp2.getSalary()) return 0;
       return 1;
    }
}

A shorter way to write the comparison would be like this:


public class MyComparator<Employee> implements Comparator<Employee> {
    public int compare(Employee emp1, Employee emp2){
       return emp1.getSalary() - emp2.getSalary();
    }
}

By subtracting one salary from the other, the resulting value is automatically either negative, 0 or positive.

If you want to compare objects by more than one factor, start by comparing by the first factor (e.g. first name). Then, if the first factors are equal, compare by the second factor (e.g. last name, or salary) etc.

Resolving Excel Export I/O Stream Error/Fatal Error Issue

Problem:

    Fatal Application Error while exporting search results data into an excel sheet.

Root Cause for the Issue is:


  1. The Root Cause of the issue is Because of using the global (Instance) variables instead of using the method variables inside the class for writing the data to the excel file.

  1. In Struts 1.1/1.2 the Action class behaves like singleton. There will be only one instance of the action for all the incoming requests. So whenever we try to build our logic using the instance variables (The variables which we are defining at the top of the class outside the method area) instead of local variables (or method variables), we will face data inconsistency issues. If we are using this kind of variables for IO operations then we will be ending with Stream errors (like the one we faced in one of our application recently).


  1. In the case of our (XYZ) application, there was a call to flushRows(100) function on the global variable which variable was declared outside the method (at the beginning of the respective action class). So whenever two requests raised simultaneously, Out of two requests one request was taking less time to complete the job, during completion of this request the I/O stream was  closed after the call to flushRows() function or call to out.close(). So when another request starts processing on the same, that time it finds the I/O stream closed and it cannot proceed the request and was throwing "Stream Closed" exception. Because it was unable to read or write to the stream once it was closed. Since the same copy of instance variable has been used for both the request, one user request finds the modified variable by another request which is not correct behavior.
  

Solution:

       To avoid this problem there are three approaches which I proposed, out of three I felt the last one is the best approach:

  1. Moving all Excel export code to different function and using local variables to that function instead of global (instance) variables. Implementing this functionality in a separate method inside the action class. But this is not a good approach as action comes under view layer and excel export needs to be implemented in the business layer. And also here we are not separating the excel functionality to another class which is not a proper design. But as immediate fix we can go ahead with this approach if your implementation already in some action class and you don’t have much time.  

  1. Moving all excel related code to the different class and calling these methods from the current action class. Here the advantage is we are separating the excel related business logic from the action layer code. One good thing about this approach is that we are separating the Excel Export functionality code to different class, but the bad thing about this is, we are calling this class from action class i.e. from view layer which is not a correct design. This we can just keep as one immediate solution for our problem.


  1. The Best approach is to move all the Excel related functionalities to one utility class and call the respective method from Model Layer (Business layer, where business logic implemented). And avoid use of instance variables for Excel export implementation especially for multithreaded application. If at all using you have to take care of all the scenarios which is a very big headache. And also proper exception handling and proper cleaning of the I/O resources once after completing the job is very important to avoid errors.

Disabled Form Fields Strange Behavior

Disabled form fields of html will not get the values (or will get null) after submitting the Form: 

Code like below for the input form fields in HTML will generate the disabled field. Disabled field is the one which is not editable, not focusable, won’t get tab navigation, and can’t select the field. These are the characteristics of the disabled form field. We can apply this attribute on all input fields, buttons, select box, etc. 

Please find the code below:

<input type=”text” name=”accountNumber” value=”123455” disabled=”disabled”   />

The above code will generate the disabled text field where we can’t be able to edit and select the field.

Characteristics of Disabled form fields:


1)   Disabled form field cannot be focusable, i.e. you cannot focus the field.
2)   Disabled fields are non-editable.
3)   Disabled fields will not be submitted when submission of form happens or when we will click on ‘Submit’ button.
4)   Disabled fields will give null values after submitting the form where you are getting the values (it may be struts action class in case of struts or servlet class in case of servlets.
5)   We can modify the values of disabled fields only through JavaScript at client side.

How to get disable behavior for any of the input field and also getting the non-null values after form submission:


1)   Make the field ‘readOnly’ instead of ‘disabled’ one by putting the attribute as ‘readonly=”readonly”’ for html fields and ‘readOnly=”true”’ for struts JSP fields.

2)   Prepare the CSS with the color of disabled fields (i.e. gray color), and apply this CSS to the fields which you made as readonly. Now the field is non-editable because of readonly attribute and looks like disabled field because of the CSS applied.

Characteristics of ‘readonly’ fields:


1)   Fields are not editable through the screen.
2)   Fields can be modified through JavaScript code at client side.
3)   Fields can be Focusable.
4)   Fields can be selectable.
5)   Tab navigation possible on the fields.
6)   Values can be submitted after form submission.
7)   No null values after form submission whenever field contains values while submitting.

This will solve the issue with disabled fields used in the view layer for specific purpose and will help to get the disabled behavior.

Top 15 Java Web sites

Tuesday, September 23, 2014

Useful Java Debugging Tips with Eclipse


In this tutorial we will see about debugging java applications using Eclipse. Debugging helps us to identify and fix defects in the application. We will focus on run-time issues and not compile time errors. There are command line debuggers like gdb available. In this tutorial we will focus on GUI based debugger and we take our favorite IDE Eclipse to run through the tutorial. Though we say Eclipse, the points are mostly generic and is suitable for debugging using most of the IDEs like NetBeans too.

Do not use System.out.println as a tool to debug.
  • Enable detailed log level of all the components involved.
  • Use a log analyzer to read logs.


1. Conditional Breakpoint
Hope we know how to add a breakpoint. If not, just click on the left pane (just before the line number) and a breakpoint will be created. In debug perspective, ‘Breakpoints’ view will list the breakpoint created. We can add a boolean condition to it. That is, the breakpoint will be activated and execution will hold only if the boolean condition is met otherwise this breakpoint will be skipped.


  
2. Exception Breakpoint
In Breakpoints view there is a button labeled as J! We can use that button to add a java exception based breakpoint. For example we want the program to halt and allow to debug when a NullPointerException is thrown we can add a breakpoint using this.



3. Watch Point
 When a chosen attribute is accessed or modified program execution will halt and allow to debug. Select a class variable in Outline view and from its context menu select Toggle Watchpoint. This will create a watch point for that attribute and it will be listed in Breakpoints view.



4. Evaluation (Display or Inspect or Watch)
Ctrl+Shift+d or Ctrl+Shift+i on a selected variable or expression will show the value. We can also add a permanent watch on an expression/variable which will be shown in Expressions view when debug is on.



5. Change Variable Values
We can change the value of a variable on the fly during debug. Choose a variable and go to Variables view and select the value, type and enter.



6. Stop in Main
In Run/Debug Settings, Edit Configuration we can enable a check box that says Stop in main. If enabled when we debug a java program that launches with a main method, the execution halts at first line of main method.


7. Environment Variables
Instead of going to System properties to add an environment variable, we can conveniently add it through Edit Configuration dialog box.



8. Drop to Frame
This is the second best feature I love. We can just return the control to any frame in the call stack during debug. Changes made to variables will not be reset. Choose the stack level which you want to go back and restart debug from there and click the drop to frame button from debug toolbar. Eclipse is cool!



 9. Step Filter
When we Step Into (F5) a method we may go into external libraries (like java) and we may not need it. We can add a filter in preferences and exclude packages.



10. Step Into, Over and Return
I kept this as the last point as this is the first thing to learn in debugging :-)
  • F5 – Step Into: moves to next step and if the current line has a method call the control will go into the first line of the called method.
  • F6 – Step Over: moves the control to next line. If there is a method call in the current line, it executes the method call internally and just moves the control to next line.
  • F7 – Step Return: When done from inside a method the control will move to the calling line from where the current method is invoked.
  • F8 – Move to next breakpoint.