Google+ Java Geek Zone

Tuesday, 3 November 2015

On 04:06 by Unknown in ,    No comments
Plugin Name Description Update URL Website
EclEmma EclEmma is a free Java code coverage tool for Eclipse


PMD PMD is a source code analyzer. It finds common programming flaws like unused variables, empty catch blocks, unnecessary object creation, and so forth. It supports Java, JavaScript, PLSQL, Apache Velocity, XML, XSL. Additionally it includes CPD, the copy-paste-detector. CPD finds duplicated code in Java, C, C++, C#, PHP, Ruby, Fortran, JavaScript, PLSQL, Apache Velocity, Ruby, Scala, Objective C, Matlab, Python, Go.

 https://pmd.github.io/


Wednesday, 28 October 2015

On 07:01 by Unknown in , , , ,    2 comments
We all know in java ArrayList does not have limit unlike Array where we can only add fixed number of elements.

ArrayList allows dynamically adding and removing the elements in this list. So question comes HOW?

By default initial capacity of an array is defined with constant DEFAULT_CAPACITY

private static final int DEFAULT_CAPACITY = 10;


If we closely look at the add method in the source code of ArrayList.java. Click here to get whole file.

public boolean add(E e)
    
{
   
     ensureCapacity(size+1);
     elementData[size++] = e;         
     return true;
}



We can see in above code that before adding the element into the ArrayList its calling one method named “ensureCapacity”. This method makes sure what is the current size of the existing elements containing in the array and what is the maximum allowed size for the array at this point of time?

So if we are trying to add more element than its maximum allowed size then maximum allowed size needs to be increased in order to accommodate new elements.

But here we must notice that “elementData” is an array only and array does not grow dynamically.

private transient Object[] elementData; 


Here is the main thing to notice

Internally new array is created with new capacity and then elements from existing array are copied to the new array with bigger capacity.

elementData = Arrays.copyOf(elementData, newCapacity);

New capacity is calculated with below expression:

int newCapacity = (oldCapacity * 3)/2 + 1;


If you want to see this happening, You can try to execute the below code snippet in debug mode and monitor elementData array as shown in below figure.




package com.javageekzone.collection;

import java.util.ArrayList;
import java.util.List;

public class ArrayListExample 
{
 public static void main(String[] args) 
 {
  List list = new ArrayList();

  for (int counter = 1; counter < 1000; counter++) 
  {
   list.add(counter);
  }
 }
}


































































I hope you now know how the size of ArrayList grows dynamically. Please let me know by comments if you still have any doubts.

Cheers!!!

Monday, 26 October 2015

On 06:03 by Unknown in , , ,    No comments
In most of the interviews of Java, We are often checked with the in depth knowledge of Collection APIs and its capabilities.

One of the very famous interview questions is: Why Set does not allow duplicate value?

Now, don’t tell me you were also asked the same

We all know Set theory in mathematics that all elements in Set are always unique. The same has been applied to the Set API. Let’s try to understand this with very small java code snippet.

Basically I want to add elements in Set where I want to try adding some duplicates as well as shown below.

package com.javageekzone.collection;

import java.util.HashSet;
import java.util.Set;

public class DuplicateSetElements {
public static void main(String[] args) {
 
 Set subjects=new HashSet();
 
 
 subjects.add("Spring");
 subjects.add("Java");
 subjects.add("Oracle");
 
 System.out.println("Subjects: "+subjects);
 
 subjects.add("Java");
 subjects.add("Cobol");
 subjects.add("Spring");
 
 System.out.println("Subjects: "+subjects);
}
}



In above code we are invoking add method to insert the element. Let’s see the source code of this method in the class HashSet.java.

public class HashSet&ltE&gt extends AbstractSet&ltE&gt implements Set&ltE&gt, Cloneable, java.io.Serializable
{
    private transient HashMap&ltE,Object&gt map;
    
    // Dummy value to associate with an Object in the backing Map
    
    private static final Object PRESENT = new Object();
    
    
    
    public HashSet() {
        map = new HashMap<>();
    }
    
    // More Code goes here ,i.e Other methods in Hash Set
    
    
    public boolean add(E e) {
        return map.put(e, PRESENT)==null;
    }
    
    
    
    // More Code goes here ,i.e Other methods in Hash Set
}

Above code is part of rt.jar file in your jre under java/util package. Click here to get full code.

You can see below facts in the HashSet.java
  1. When you instantiate HashSet it’s actually instantiating HashMap in the constructor
  2. PRESENT is the member variable of the HashSet which is instantiated with type Object and it acts as dummy value which it passes to put method.
  3. In the add method implementation internally its calling put method of the HashMap.
  4. put method is considering actual value passed in add method as key and PRESENT as value.
So if I try to add the element “java” by add method.

subject.add(“java”)

It will put that element E here “java” as a key in the HashMap and the dummy value PRESENT as a value to the key.

Now if you look at the code of the HashMap’s put(Key k,Value V) method , you will see put method something like this

public V put(K key, V value) 
{
    //Some code goes here
}

Here we can notice that put (key,value) will
  1. return NULL if the key is unique and the element is added to the map.
  2. return old value of the key if key is duplicate.
Hence , in HashSet add() method ,  it check the return value of map.put(key,value) method with null value i.e

public boolean add(E e) 
{
    return map.put(e, PRESENT)==null;
}

So , if map.put(key,value) returns null ,then

map.put(e, PRESENT)==null will return true and element is added to the HashSet.

So, if map.put(key,value) returns old value of the key ,then

map.put(e, PRESENT)==null will return false and element is  not added to the HashSet .

Conclusion: HashSet internally utilize HashMap to facilitate the storage and uniqueness of the element.

I hope you are clear with this internal mechanism now. If you still have any doubt please feel free to contact me.

Cheers!!!

Friday, 23 October 2015

On 08:27 by Unknown in , , ,    No comments
Below are few Eclipse shortcuts which can make your life easier/faster to work with it.

1. Manage Files and Projects
Ctrl+N Create new project using the Wizard
Ctrl+Alt+N Create new project, file, class, etc.
Alt+f, then . Open project, file, etc.
Ctrl+Shift+R Open Resource (file, folder or project)
Alt+Enter Show and access file properties
Ctrl+S Save current file
Ctrl+Shift+S Save all files
Ctrl+W Close current file
Ctrl+Shift+W Close all files
F5 Refresh content of selected element with local file system

2. Editor Window
Focus/ cursor must be in Editor Window for these to work.
F12 Jump to Editor Window
Ctrl+Page Down/Ctrl+Page Up Switch to next editor / switch to previous editor
Ctrl+M Maximize or un-maximize current Editor Window (also works for other Windows)
Ctrl+E Show list of open Editors. Use arrow keys and enter to switch
Ctrl+F6/Ctrl+Shift+F6 Show list of open Editors. Similar to ctrl+e but switches immediately upon release of ctrl
Alt+Arrow Left/Alt+Arrow Right Go to previous / go to next Editor Window
Alt+- Open Editor Window Option menu
Ctrl+F10 Show view menu (features available on left vertical bar: breakpoints, bookmarks, line numbers, …)
Ctrl+F10, then n Show or hide line numbers
Ctrl+Shift+Q Show or hide the diff column on the left (indicates changes since last save)

3. Navigate in Editor
Home/End Jump to beginning / jump to end of indention. Press home twice to jump to beginning of line
Ctrl+Home/End Jump to beginning / jump to end of source
Ctrl+Arrow Right/Arrow Left Jump one word to the left / one word to the right
Ctrl+Shift+Arrow Down/Arrow Up Jump to previous / jump to next method
Ctrl+L Jump to Line Number. To hide/show line numbers, press ctrl+F10 and select 'Show Line Numbers'
Ctrl+Q Jump to last location edited
Ctrl+./Ctrl+, Jump to next / jump to previous compiler syntax warning or error
Ctrl+Shift+P With a bracket selected: jump to the matching closing or opening bracket
Ctrl+[+]/Ctrl+- on numeric keyboard Collapse / Expand current method or class
Ctrl+[/]/Ctrl+* on numeric keyboard Collapse / Expand all methods or classes
Ctrl+Arrow Down/Ctrl+Arrow Up Scroll Editor without changing cursor position
Alt+Page Up/Alt+Page Down Next Sub-Tab / Previous Sub-Tab

4. Select Text
Shift+Arrow Right/Arrow Left Expand selection by one character to the left / to the right
Ctrl+Shift+Arrow Right/Arrow Left Expand selection to next / previous word
Shift+Arrow Down/Arrow Up Expand selection by one line down / one line up
Shift+End/Home Expand selection to end / to beginning of line
Ctrl+A Select all
Alt+Shift+Arrow Up Expand selection to current element (e.g. current one-line expression or content within brackets)
Alt+Shift+Arrow Left/Arrow Right Expand selection to next / previous element
Alt+Shift+Arrow Down Reduce previously expanded selection by one step

5. Edit Text
Ctrl+C/Ctrl+X/Ctrl+V Cut, copy and paste
Ctrl+Z Undo last action
Ctrl+Y Redo last (undone) action
Ctrl+D Delete Line
Alt+Arrow Up/Arrow Down Move current line or selection up or down
Ctrl+Alt+Arrow Up/Ctrl+Alt+Arrow Down/ Duplicate current line or selection up or down
Ctrl+Delete Delete next word
Ctrl+Backspace Delete previous word
Shift+Enter Enter line below current line
Shift+Ctrl+Enter Enter line above current line
Insert Switch between insert and overwrite mode
Shift+Ctrl+Y Change selection to all lower case
Shift+Ctrl+X Change selection to all upper case

6. Search and Replace
Ctrl+F Open find and replace dialog
Ctrl+K/Ctrl+Shift+K Find previous / find next occurrence of search term (close find window first)
Ctrl+H Search Workspace (Java Search, Task Search, and File Search)
Ctrl+J/Ctrl+Shift+J Incremental search forward / backwards. Type search term after pressing ctrl+j, there is now search window
Ctrl+Shift+O Open a resource search dialog to find any class

7. Indentions and Comments
Tab/Shift+Tab Increase / decrease indent of selected text
Ctrl+I Correct indention of selected text or of current line
Ctrl+Shift+F Autoformat all code in Editor using code formatter
Ctrl+/ Comment / uncomment line or selection ( adds '//' )
Ctrl+Shift+/ Add Block Comment around selection ( adds '/... */' )
Ctrl+Shift+\ Remove Block Comment
Alt+Shift+J Add Element Comment ( adds '/** ... */')

8. Editing Source Code
Ctrl+Space Opens Content Assist (e.g. show available methods or field names)
Ctrl+1 Open Quick Fix and Quick Assist
Alt+/ Propose word completion (after typing at least one letter). Repeatedly press alt+/ until reaching correct name
Ctrl+Shift+Insert Deactivate or activate Smart Insert Mode (automatic indention, automatic brackets, etc.)

9. Code Information
Ctrl+O Show code outline / structure
F2 Open class, method, or variable information (tooltip text)
F3 Open Declaration: Jump to Declaration of selected class, method, or parameter
F4 Open Type Hierarchy window for selected item
Ctrl+T Show / open Quick Type Hierarchy for selected item
Ctrl+Shift+T Open Type in Hierarchy
Ctrl+Alt+H Open Call Hierarchy
Ctrl+U Find occurrences of expression in current file
Ctrl+move over method Open Declaration or Implementation

10. Refactoring
Alt+Shift+R Rename selected element and all references
Alt+Shift+V Move selected element to other class or file (With complete method or class selected)
Ctrl+Shift+C Change method signature (with method name selected)
Alt+Shift+M Extract selection to method
Alt+Shift+L Extract local variable: Create and assigns a variable from a selected expression
Alt+Shift+I Inline selected local variables, methods, or constants if possible (replaces variable with its declarations/ assignment and puts it directly into the statements)

11. Run and Debug
Ctrl+F11 Save and launch application (run)
F11 Debug
F5 Step Into function
F6 Next step (line by line)
F7 Step out
F8 Skip to next Breakpoint

12. The Rest
Ctrl+F7/Ctrl+Shift+F7 Switch forward / backward between views (panels). Useful for switching back and forth between Package Explorer and Editor.
Ctrl+F8/Ctrl+Shift+F8 Switch forward / backward between perspectives
Ctrl+P Print
F1 Open Eclipse Help
Shift+F10 Show Context Menu right click with mouse

13. Team (SVN Subversive)
Ctrl+Alt+S Synchronize with Repository
Ctrl+Alt+C Commit
Ctrl+Alt+U Update
Ctrl+Alt+D Update to Revision
Ctrl+Alt+E Merge
Ctrl+Alt+T Show Properties
Ctrl+Alt+I Add to svn:ignore
On 01:42 by Unknown in , , ,    No comments
Often we write the code and import the classes in the import section of the class file.

Code never stays unchanged for lifetime as change is the only constant thing in programming.

Many times, after code refactoring or bug fixed, Eclipse IDE will show a yellow underline for all unused imports at the top of your class and said “The import xxx is never used

When we change the code sometimes we forget to remove the old imported classes under import section. Keeping something which is never used in code is not considered a good practice.

Eclipse provides multiple options to get rid of those unused imports. I will explain all the options available in eclipse to achieve this.

Option-1

This option is not much useful as it only works for single line and not for all unused import in whole class.

  1. Open your class file
  2. Go to the line of unused import
  3. Press ctrl + 1 which is a eclipse shortcut of quick fix, this will display a drop down menu to fix this and you will see an option "remove unused imports"
  4. Click  on "remove unused imports"


Option-2

This option will remove all unused imports from whole class.

  1. Open your class file
  2. Right click on code area
  3. Go to “Source”
  4. Click on “Organize Imports”


Option-3


This option will also remove all unused imports from whole class.

  1. Open your class file
  2. Press Shift + Ctrl + O  for PC or Command + Shift + O  for Mac
Advance Options :

Option-4


This option will allow you to remove all unused imports when you save your class file

  1. Click on “Window”
  2. Click on “Preferences”
  3. Select & Expand “Java”
  4. Select & Expand “Editor”
  5. Click on “Save Actions”
  6. Check the option “Perform the selected actions on save”
  7. Check the option “Organize Imports”
  8. Click on “Apply” in Preference window
  9. Click on “OK” in Preference window


Above option also allows you to set preference for formatting source code and invoking other additional actions.

Option-5

This option will allow you to remove all unused imports from all class files of your package. It’s very nice and efficient option to achieve this in one go.

  1. Go to “Project Explorer”
  2. Right click on your package
  3. Go to “Source”
  4. Click on “Organize Imports”


Option-6

This option will allow you to remove all unused imports from all class files of your package/project. You can configure this setting in Eclipse [built-in] profile or you can create your own profile for the same. I will show you by creating your own profile and configuring it.

Configuration Actions:

  1. Click on “Window”
  2. Click on “Preferences”
  3. Select & Expand “Java”
  4. Select & Expand “Code Style”
  5. Click on “Clean Up”


  6. Click on “New”
  7. Enter the “Profile Name” of your choice
  8. Click on “OK”
  9. Go to Tab “Code Organizing”
  10. Check the option “Organize Imports”
  11. Click on “Apply” in profile window
  12. Click on “OK” in profile window
  13. Click on “Apply” in preference window
  14. Click on “OK” in preference window


Executing Actions:

  1. Go to “Project Explorer”
  2. Right click on your package
  3. Go to “Source”
  4. Click on “Clean Up”
  5. Choose a profile you configured.
  6. Click on “Next”
  7. Click on “Finish”




That is all about the options to remove unused imports from the class files.

I hope these options will make your life easier to work with eclipse and make code neat and cleaner.

I will come up with more eclipse tips soon till then happy coding… 

Cheers!!!

Friday, 1 August 2014

On 03:49 by Unknown in , ,    1 comment
Hi Friends,

Are you facing issue in Eclipse while searting tomcat in debugging mode?

Some times Eclipse tries to start tomcat in debugging mode and it gives below mentioned error message.

“Server Tomcat v6.0 Server at localhost was unable to start within 45 seconds. If the server requires more time, try increasing the timeout in the server editor.”















The message itself says you can try increasing the timeout in server editor and we all will try searching it in eclipse settings. But you could not find it right?

Do not worry this issue can easily be fixed with minor configuration in workspace\.metadata\.plugins\org.eclipse.wst.server.core\server.xml

Navigate to the above mentioned location in your Eclipse project workspace and open the file in any text editor.

You will see xml configuration similar to below


 
 
 

Look for start-timeout=”45″ and change it to big value like start-timeout=”145″

You are done!!! Restart the workspace and try now.

Hope this will help you…

Cheers!!!
On 03:34 by Unknown in , ,    1 comment
If your code is using Servlet.getRealPath() and Weblogic Server[WLS] returns null . You might be thinking that it's one more weblogic server bug but it's not a bug.

It depends on how you deploy your application. If the application was deployed using exploded mode, getRealPath returns occured, valid value. But if you deploy application as an archive having extentions like ear, war etc. you will get "null pointer" Exception.

Good news is,There are two simple way to solve this exception.

1. you can solve this issue in domain level, setting weblogic Admin Console option Domain | Web Application | Archived Real Path Enabled to true, as mentioned below:



You can also correct this issue in application level by configuring below mentioned entry to weblogic.xml file in your application:


true


Cheers!!!