Rabu, 26 Februari 2014

List of special bash parameter used in Unix or Linux script






Meaning of bash parameter used in Unix script


Many of us use bash script for doing housekeeping and other stuff but occasionally and not much aware of special bash parameters. When I was new to bash shell and Linux and looking on some already written bash script I used to get baffled with special bash symbols like $@, $_, $1 etc. I did know that they are bash parameter and has special meaning but I don't have all meanings of special bash parameter on top of my head and I always go to Google and search endlessly for those special bash parameter, some time I got and found meaning of those special bash script parameters quickly but sometime I need spend some time to get what I am actually looking for, so I thought to document meanings and expansion of those special bash parameters or bash script parameters.



This bash script parameter tutorial is in continuation of my earlier UNIX tutorials find examples in UNIX, grep command examples in UNIX, and UNIX networking commands tutorial if you haven’t read already you may find them interesting and useful.









The list which I am going to share with you guys today is what I have accumulated over the years. This list of special bash parameters are by no means complete and only contains some of the bash script parameters which I have encountered , so please contribute any bash parameter which is not in this list and you found useful.






What are special bash parameters?







spcial bash parameters and bash script parameters

Special bash parameters are those parameters which bash shell treats especially when encounters in bash script in Linux or UNIX system. Important point of these bash script parameters is that they can only be referenced and you can not assign any value to them. Apart from special bash parameters I have also listed down meaning of special bash characters for quick reference e.g. "&"  ">" ">>“, these special bash characters are quite useful while working in bash shell in UNIX or Linux environment. I know remembering these special bash parameters and special characters is quite tricky specially when you write bash script occasionally but at the same time you need to understand it to read existing bash scripts written by someone like bash script experts. What I do is I keep this in a place which is quite handy and just search whenever I come across any special bash parameters.








Special bash parameters and there meaning













Special bash parameter Meaning
$! $! bash script parameter is used to reference the process ID of the most recently executed command in background.
$$      $$ is used to reference the process ID of bash shell itself
$#      $# is quite a special bash parameter and it expands to number of positional parameters in decimal.
$0 $0 bash parameter is used to reference name of the shell or shell script. so you can use this if you want to print name of shell script.
$-      $- (dollar hyphen) bash parameter is used to get current option flags specified during invocation, by the set built-in command or set by the bash shell itself. Though this bash parameter is rarely used.
$?      $0 is one of the most used bash parameter and used to get the exit status of the most recently executed command in foreground. By using this you can check whether your bash script is completed successfully or not.
$_ $_ (dollar underscore) is another special bash parameter and used to reference the absolute file name of the shell or bash script which is being executed as specified in the argument list. This bash parameter is also used to hold the name of mail file while checking mails.
$@      $@ (dollar at the rate) bash parameter is used to expand into positional parameters starting from one. When expansion occurs inside double quotes, every parameter expands into separate words.
$*      $* (dollar star) this is similar to $@ special bash parameter  only difference is when expansion occurs with double quotes, it expands to a single word with value of each bash parameter separated by the first character of the IFS special environment variable.




Example of passing parameter to bash script in Unix:


Many times we require passing parameter to bash script. Now let’s see an example of bash script on which we will pass bash parameter from command prompt and will access them inside bash script. This example will help you to understand the use of special bash parameters much better.


$ cat bashparameterexample.sh

#!/bin/bash

 

if [ $# -lt 2 ]   -- $# is used for number of arguments

then

  echo "Usage: $0 arg1 arg2"

  exit

fi

 

echo -e  "\$1=$1" -- $1 is used to access first parameter

echo -e "\$2=$2"  -- $2 is used to access second parameter




Now lets invoke the bash script without parameter, it will print the “usage “statement because $# is less than 2, now you see how useful “$#” is for writing script J


Javin@stocktrading ~

$ ./bashparameterexample.sh      

Usage: ./bashparameterexample.sh arg1 arg2


 

Now lets pass two parameters to the script and access them via $1 and

 $2 its really fun writing bash script once you are familiar with bash parameters.

 


Javin@stocktrading ~

$ ./bashparameterexample.sh  23 44

$1=23

$2=44





Difference between $* and $@ bash parameters


$* and $@ both are used to access full list of positional parameters supplied during invocation of bash script and you can iterate through them using bash for loop. $* and $@ are special bash parameters and if used without double quotes then both will behave identical i.e. they will provide the list of positional parameter starting from first parameter $1 and each of those will be separated by space.



For example if your provide 5 parameters during invocation of bash script $@ and $* will expand into $1 $2 $3 $4 $5



But if you double quotes then they will behave differently, in case of $* individual parameters will be separated by first char of IFS characters while in case of $@ individual parameters will appear in quotes and separated by space.








Special bash characters and there meaning


We have just seen special bash script parameters and there meaning and now we will some special bash characters and what they mean when used inside bash script or in bash shell command prompt. We will also see special bash characters called redirection characters which is used to redirect input, output etc



























Special bash character Meaning
# # is used to comment a single line in bash script
$$ $$ is used to reference process id of any command or bash script
$0      $0 is used to get name of command in bash script.
$name      $name will print the value of variable “name” defined in script.
$n      $n will print value of nth argument provided to bash script (n ranges form 0 to 9) e.g. $1 will print first argument.


>  > is used to redirect output
>>  >> can be used to Append to file
<  < will redirect input


[ ] [] are for matching any characters enclosed
( ) Execute in sub shell
` ` Another powerful special bash character which is used to substitute output of enclosed command
" " Partial quote (allows variable and command expansion)
' ' Full quote (no expansion)
\ Quote following character


| Pipe output of one command to another most useful and immensely power bash character
& & is used to run any process in background.
; ;(semi colon ) is used to separate commands on same line
* * is used to match any character(s) in filename
? ? is for matching single character in filename



Knowledge of special bash parameters and special bash characters will make you more comfortable while reading and understand already written bash scripts. It is this cryptic bash parameter which makes the script more complex or reading but at same time can be immensely useful if know how to use them. These special bash parameters can be used in any bash script.






Some more UNIX Command tutorials





























Source:http://javarevisited.blogspot.com/2011/06/special-bash-parameters-in-script-linux.html

3 Exampls to Convert an Array to ArrayList in Java



How to convert an array to ArrayList in Java
Have you encountered any situation where you quickly wanted to convert your array to ArrayList or ArrayList to array in Java? I have faced many such situations which motivate me to write these quick Java tips about converting array to ArrayList and ArrayList to array in Java. Both array and ArrayList are quite common and every Java developer is familiar with this. Former is used to store object and primitive type while later can only hold objects. Array is part of standard Java fundamental data structure while ArrayList is part of collection framework in Java. Most of the time we store data in form of object in either Array or ArrayList or sometime we find either of them suitable for processing and we want to convert from one array to ArrayList or ArrayList to array in Java. This short array to ArrayList tutorial in Java will explain how quickly you can convert data from each other. So when you face such situation don't bother just remember this tips and you will get through it. If you compare array vs ArrayList only significant different is one is fixed size while other is not. This article is in continuation of my post Difference between Vector and ArrayList in Java and How to Sort ArrayList in Java on descending order. On related not from Java 5 onwards ArrayList class supports Generics in Java, which means you can convert an ArrayList of String into an String array or ArrayList of Integer into an Integer Array. Generics provides type safety and remove casting during runtime.




How to convert Array to ArrayList in Java


In first section of this Java tutorial we will see how to convert from Array to ArrayList while in second section we will see opposite of it i.e. from ArrayList to Array. Main difference between these two is that once declared you can not change the size of former while later is dynamic which re-sizes itself whenever its capacity crossed threshold specified by load factor. So you can say former is fixed-size and you later are re-sizable. java.util.Arrays class act as a bridge between array to ArrayList  and used to convert from array to ArrayList or ArrayList  to array. If you like to learn more about Array you may check How to detect if Array contains duplicate or not and How to sort Array elements in Java in ascending order.




Using Arrays.asList() method


Look at the below example, we have an array which contains different kind of asset class e.g. equity, gold and foreign exchange etc and we want to convert into an arraylist. This is the simplest way of converting from array to ArrayList.

String[] asset = {"equity", "stocks", "gold", "foreign exchange","fixed income", "futures", "options"}; 
List<String> assetList = Arrays.asList(asset);


Its worth to note following point while using Arrays.asList() method for array to arraylist conversion:

1) This method returns a List view of underlying array.


2) List returned by this method would be fixed size.


3) Most important point to note is when you change an element into this List corresponding element in original array will also be changed.


4) Another important point is since List is fixed size, you can not add element into it. If you try you will get exception.


5) This is the most efficient way of converting array to arraylist as per my knowledge because it doesn't copy the content of underlying array to create list.


6) From Java 5 or JDK 1.5 onwards this method supports generic so you can generate type safe ArrayList from array. to know more about Generic see my post How Generic works in Java


One of the most important point related to Arrays.asList() method is that it returns a fixed size List not a read only List, although you can not add() or remove() elements on this List you can still change existing elements by using set method. If you are using this to create read only List than its wrong, Use Collections.unmodifiableList method to create read only collection in Java.





Array to ArrayList by using Collections.addAll method



convert array to arraylist in Java program

This example of converting an array to ArrayList is not that efficient as the earlier method but its more flexible.

List<String> assetList = new ArrayList();
String[] asset = {"equity", "stocks", "gold", "foriegn exchange", "fixed income", "futures", "options"};

Collections.addAll(assetList, asset);



Important point about this method of array to ArrayList conversion is :


1) Its not as fast as Arrays.asList() but more flexible.


2) This method actually copies the content of the underlying array into ArrayList provided.


3) Since you are creating copy of original array, you can add, modify and remove any element without affecting original one.


4) If you wan to provide individual element you can do so by specifying them individually as comma separated. Which is a very convenient way of inserting some more elements into existing list for example we can add some more asset classes into our existing assetlist as below?
Collections.addAll(assetList, "Equity Derivatives", "Eqity Index Arbitrage" , "Mutual Fund");











Example of Converting ArrayList to Array using Collection's addAll method


This is another great way of converting an array to ArrayList. We are essentially using Collection interface's addAll() method for copying content from one list to another. Since List returned by Arrays.asList() is fixed-size it’s not much of use, this way we can convert that into proper ArrayList.

Arraylist newAssetList = new Arraylist();
newAssetList.addAll(Arrays.asList(asset));





These were the three methods to convert an array to ArrayList in Java. By the way, you can also create arrays of ArrayList because list can hold any type of object.






Array to List in Java using Spring Framework


There is another easy way of converting array to ArrayList if you are using spring framework. spring framework provides several utility method in class CollectionUtils, one of the is CollectionUtils.arrayToList() which can convert an array into List as shown in below example of array to List conversion using spring framework. It’s worth noting though List returned by arrayToList() method is unmodifiable just like the List returned by Arrays.asList(), You can not add() or remove() elements in this List. Spring API also provides several utility method to convert an ArrayList into comma separated String in Java.

String [] currency = {"SGD", "USD", "INR", "GBP", "AUD", "SGD"};
System.out.println("Size of array: " + currency.length);
List<String> currencyList = CollectionUtils.arrayToList(currency);

//currencyList.add("JPY"); //Exception in thread "main" java.lang.UnsupportedOperationException
//currencyList.remove("GBP");//Exception in thread "main" java.lang.UnsupportedOperationException

System.out.println("Size of List: " + currencyList.size());
System.out.println(currencyList);






How to convert ArrayList to Array in Java


Now this is a opposite side of story where you want to convert from Arraylist to Array, instead of array to ArrayList, interesting right. Just now we were looking at converting array to arraylist and now we need to back to former one. Anyway it’s simpler than you have probably thought again we have java.util.Arrays class as our rescue. This class acts as bridge between ArrayList to array.



Example of converting ArrayList to Array in Java


In this example of ArrayList to array we will convert our assetTradingList into String array.
ArrayList assetTradingList = new ArrayList();                       

assetTradingList.add("Stocks trading");
assetTradingList.add("futures and option trading");
assetTradingList.add("electronic trading");
assetTradingList.add("forex trading");
assetTradingList.add("gold trading");
assetTradingList.add("fixed income bond trading");
String [] assetTradingArray = new String[assetTradingList.size()];
assetTradingList.toArray(assetTradingArray);


After execution of last line our assetTradingList will be converted into String array. If you like to learn more about How to use ArrayList in Java efficiently check the link it has details on all popular operation on Java ArrayList.






Getting a clear idea of converting array to ArrayList and back to ArrayList and array saves a lot of time while writing code. It’s also useful if you like to initialize your ArrayList with some default data or want to add some elements into your existing ArrayList. these examples of converting array to ArrayList is by no means complete and please share your own ways of converting from ArrayList to array and vice-versa. If you are preparing for Java interview, don't forget to check my list of Top 25 Java Collection framework interview questions for experienced programmers.
























Source:http://javarevisited.blogspot.com/2011/06/converting-array-to-arraylist-in-java.html

10 example of using Vim or VI editor in UNIX and Linux






Vim or VI editor tutorial in UNIX


vi editor in unixVI Editor is like notepad in UNIX but it’s extremely powerful and have sophisticated feature to work as complete IDE. No matter which version of UNIX you are working or which flavor you are using you always find either VI editor or VIM there. VI is a very large topic and I am not covering every aspect of it what I am sharing here is some examples of using VI editor in UNIX or Linux. most of the time we use only 10% of VI editor and never know 90% of it , to be frank I also don't know many of VI feature by heart but I always search for it , see people working in VI and learn from there experience as well. after working on VI editor what I found that every day we learn something new in VI editor but we  forget something equally important and there I thought lets document whatever VI commands I have learned so far and using regularly. Idea is to keep this VI Editor tutorial updated with every single useful VI commands I learn and I also ask you guys to contribute with something useful. If you see 10 peoples working in VI editor you realize that they use it differently then use some new VI commands which you are not familiar of and which could improve your productivity as well. so if you would like to know more and more about VI editor I would suggest observe people around you when they work in VIM or VI editor and learn from there experience. Don’t confuse with both VIM and VI, VIM stands for VI improved and has some more feature than VI editor. Many a times you will find that VI command is aliased to VIM to make it default editor in UNIX.







Long story short let get into VI command examples:






Opening file in Read only mode in VI Editor


If you are in production server then you definitely want to open a config file in read only mode to avoid any accidental change. So if you are not using less you can use "-R" option of VI editor:



vim -R config.xml



And if you want to save any change from read only mode you can do by ":wq!".






Navigation commands in Vim or VI



vi editor commands in unix

One secret of being efficient in VI editor is to be fluent in navigating between different parts of file. Any time you should be able to go to start of file, end of file, start of line, end of line, and search for a particular word from up and down and then move around. Navigational commands are executed from inside VI editor, here are some of must know examples:



gg -- goes to start of file

shift g -- goes to end of file

0 -- goes to beginning of the line

$ -- goes to end of the line

nG -- goes to nth line

:n -- another way of going to nth line






Editing in VI Editor in UNIX


What do we do most in VI editor I would say editing and to become efficient and quick this is an area where you need to practice and become fluent.



yy -- equivalent to cut also called yank

p -- paste below line

shift p -- paste above line

dd -- deletes the current line

5dd -- deletes 5 lines

u -- undo last change

Ctrl + R - Re do last change




Searching pattern in VI Editor



vim editor and vi editor tutorial

Most of you guys familiar with grep command in UNIX and UNIX find command which is used for searching in Unix, here we will see how to search inside VI. If you have open your log file in VI editor and looking for any word you can search for a particular word or ID from either top to bottom or bottom to top, if you are interested in first occurrence then I would suggest to search from top to bottom on the other hand if you are interested on last occurrence then its better to search from bottom to top



/Exception  -- will search for word "Exception" from top to bottom and stop when it got first match, to go to next match type  "n" and for coming back to previous match press "Shift + N"



?Exception  -- will search for word "Exception" from bottom to top and stop when it got first match, to go to next match type  "n" and for coming back to previous match press "Shift + N", remember for next match it will go towards top of file.




Running Shell command from inside VI Editor


Some times we are editing something and we wanted to execute some shell command to get some information, normally we need to close the VI editor then execute shell command and then again open the VI editor this is not a fast way of doing it, if we want to save time and work faster we need to directly execute shell command from VI and we can do this by using "!command" from command mode of VI editor. For example doing “ls” from VI editor we can type:



:!ls



if you wants to go directly to shell without quitting from VI editor you can go by executing !sh from VI and then come back to VI editor by just executing command "exit" from  shell.






Some Useful VI Editor options




VI editor is full of options but we don't really use most of them here I am listing some of the option which I use most frequently and found quite useful.



:set nu -- This will display line number in front of each line quite useful if you want line by line information. You can turn it off by executing "set nonu". Remember for turning it off put "no" in front of option, like here option is "nu" so for turning it off use "nonu".



:set hlsearch -- This will highlight the matching word when we do search in VI editor, quite useful but if you find it annoying or not able to see sometime due to your color scheme you can turn it off by executing set nohlsearch.



:set wrap -- If your file has contains some long lines and you want them to wrap use this option, if its already on and you just don't want them to wrap use set nowrap.



:colorscheme -- color scheme is used to change color of VIM editor, my favorite color scheme is murphy so if you want to change color scheme of VI editor you can do by executing "colorscheme murphy ".



:syntax on -- syntax can be turn on and off based on your need , if its on it will display color syntax for .xml, .html and .perl files.



:set ignorecase : This VI editor option allows you do case insensitive search because if its set VI will not distinguish between two words which are just differ in case.



:set smartcase  : Another VI editor option which allows case-sensitive search if the word you are searching contains an uppercase character.






Opening multiple files in VI Editor


Sometime we just want to open 2 or 3 files in one go and then wanted to navigate on those. we can do this easily in VI editor by just giving file name separated with space while executing Vim or VI command e.g. vim file1 file2 file3 . For navigating between those file we can use option ":n"  for going to next file. You can also open any file at any time from VI editor by executing ":e filename" or reload the same file by just executing ":e" (without file name).






Saving and Quitting from VI Editor in Unix


Once we done with our change in VI editor we either wants to save or quite from the file, here are the commands to do so.



:w -- to save file anytime

:wq -- most used to save data and quit

:q! -- quit without saving

:wq! -- to save change in file opened in read-only mode.






Checking history and getting help in VI editor


if you ask me list one command you always want to remember I would say "history" because by using "history" I can get all commands I have executed in past. Same way by typing "!history" we can get all commands we have executed from VI editor. This is immensely powerful and I use it a lot. Another command which is important to remember is ":help" by typing this you can access the help system provided by VI. If you are interested on any particular command you can type ":help command" and it will display help information for that command.






find and replace in vi editor


unix vi editor exampledon't confuse this with find command in UNIX , VI editor provides easy commands to search and replace, perform global search and local search. I would suggest practice it a few times to get hold of it and understand its working. we use ":s" (substitute) command for search and replace in VI editor.



The  “:s”   command look for a particular pattern and replaces with provide substitution, here are some examples of using search and replace in VI editor.

In Vi editor search and replace, "g" stands for global search here which means all occurrence of a particular word in a line changed rather than just first word, which is default behavior if you don't use global search





:%s/Stock/Equity/g

    This is an example of global search it will replace all occurrence of word "Stock" in file with word "Equity". Its also equivalent to following command ": 0,$ s/Stock/Equity/g" which actually tells that search from fist to last line.



:%s/Stock/Equity/gc

    This is similar to first command but with the introduction of "c" it will ask for confirmation



:%s/Stock/Equity/gci

   This is command is global, case insensitive and ask for confirmation. to make it case Sensitive use "I"








Recording and replaying command in VI editor


Some times we need to perform some repetitive task and we need to execute same command again and again, you might want to consider using VI editor's recording functionality. Recoding in vim or VI editor can be done by using q and the executing recorded comment by using q@1



This list of examples of VI editor is not complete and just a collection of VI commands from top of my head. Please let me know how you are using VI editor in your day 2 day life and share some useful tips here for benefit of all. I also found vim wiki as most detailed and useful resource for VI editor and vim tips so go and learn few tips.








Related post:






























Source:http://javarevisited.blogspot.com/2011/06/vi-editor-in-unix-example-tutorial-and.html

3 ways to solve java.lang.NoClassDefFoundError in Java J2EE




I know how frustrating is to see Exception in thread "main" java.lang.NoClassDefFoundError,  which is a manifestation of NoClassDefFoundError in Java. I have seen it couple of times and spent quite a lot time initially to figure out what is wrong , which class is missing etc. First mistake I did was mingling java.lang.ClassNotfoundException and NoClassDefFoundError, in reality they are totally different, and my second mistake was using trial and error method to solve this java.lang.NoClassDefFoundError instead of understanding why NoClassDefFoundError is coming, what is real reason behind NoClassDefFoundError and how to resolve this. In this Java tutorial I have tried to rectify that mistakes and uncover some secrets of NoClassDefFoundError in Java and will share my experience around it. NoClassDefFoundError is not something which cannot be resolved or hard to resolve it’s just its manifestation which puzzles most of Java developer. This is the most common error in Java development along with java.lang.OutOfMemoroyError: Java heap space and java.lang.OutOfMemoryError: PermGen space  Anyway let’s see Why NoClassDefFoundError comes in Java and what to do to resolve NoClassDefFoundError in Java.













What is reason of NoClassDefFoundError in Java?




NoClassDefFoundError in Java comes when Java Virtual Machine is not able to find a particular class at runtime which was available during compile time. For example if we have a method call from a class or accessing any static member of a Class and that class is not available during run-time then JVM will throw NoClassDefFoundError. It’s important to understand that this is different than ClassNotFoundException which comes while trying to load a class at run-time only and name was provided during runtime not on compile time. Many Java developer mingle this two Error and gets confused.





In short NoClassDefFoundError will come if a class was present during compile time but not available in java classpath during runtime. Normally you will see below line in log when you get NoClassDefFoundError:


Exception in thread "main" java.lang.NoClassDefFoundError



Exception in thread “main” simply indicate that its “main” thread which is not able to find a particular class it could be any thread so just don’t worry . Difference between this error coming in main thread and other thread is , when Exception in thread “main” comes program crashes or shut it self down as opposed to other thread in which case your program will continue to run.,









Difference between java.lang.NoClassDefFoundError and ClassNotFoundException in Java



Many a times we confused ourselves with java.lang.ClassNotFoundException and java.lang.NoClassDefFoundError, though both of them related to Java Classpath they are completely different to each other. ClassNotFoundException comes when JVM tries to load a class at runtime dynamically means you give the name of class at runtime and then JVM tries to load it and if that class is not found in classpath it throws java.lang.ClassNotFoundException. While in case of NoClassDefFoundError the problematic class was present during Compile time and that's why program was successfully compile but not available during runtime by any reason. NoClassDefFoundError is easier to solve than ClassNotFoundException in my opinion because here we know that Class was present during build time but it totally depends upon environment, if you are working in J2EE environment than you can get NoClassDefFoundError even if class is present because it may not be visible to corresponding class loader. See my post NoClassDefFoundError vs ClassNotFoundException in Java for more details.











How to resolve java.lang.NoClassDefFoundError in Java



java.lang.NoClassDefFoundError in Java solution Obvious reason of NoClassDefFoundError is that a particular class is not available in Classpath, so we need to add that into Classpath or we need to check why it’s not available in Classpath if we are expecting it to be. There could be multiple reasons like:





1) Class is not available in Java Classpath.




2) You might be running your program using jar command and class was not defined in manifest file's ClassPath attribute.




3) Any start-up script is overriding Classpath environment variable.


4) Because NoClassDefFoundError is a sub class of java.lang.LinkageError it can also come if one of it dependency like native library may not available.




4) Check for java.lang.ExceptionInInitializerError in your log file. NoClassDefFoundError due to failure of static initialization is quite common.




5) If you are working in J2EE environment than visibility of Class among multiple Classloader can also cause java.lang.NoClassDefFoundError, see examples and scenario section for detailed discussion.





We will now see couple of example and scenarios when java.lang.NoClassDefFoundError has came before and how its been resolved. This can help you to troubleshoot root cause of NoClassDefFoundError in Java application.








NoClassDefFoundError in Java - Example and Scenarios



1. Simple example of NoClassDefFoundError is class belongs to a missing JAR file or JAR was not added into classpath or sometime jar's name has been changed by someone like in my case one of my colleague has changed tibco.jar into tibco_v3.jar and by program is failing with java.lang.NoClassDefFoundError and I was wondering what's wrong.





2. Class is not in Classpath, there is no sure shot way of knowing it but many a times you can just have a look to print System.getproperty("java.classpath")and it will print the classpath from there you can at least get an idea of your actual runtime classpath.





3. Just try to run with explicitly -classpath option with the classpath you think will work and if its working then it's sure short sign that some one is overriding java classpath.








NoClassDefFoundError in Java due to Exception in Static Initializer block




This is another common reason of java.lang.NoClassDefFoundError, when your class perform some static initialization in static block like many Singleton classes initialized itself on static block  to take advantage of thread-safety provided by JVM during class initialization process, and if static block throw an Exception, the class which is referring to this class will get NoclassDefFoundError in Java. If you look at your log file you should watch for any java.lang.ExceptionInInitializerError because that could trigger java.lang.NoClassDefFoundError: Could not initialize class on other places. Like in below code example, During class loading and initialization User class is throwing Exception from static initializer block, which trigger ExceptionInInitializerError during first time loading of User class in response to new User() call. Later rest of new User() are failing as java.lang.NoClassDefFoundError. situation gets worst if original ExceptionInInitializerError, which is root cause here is silently eaten by any code.








Code Example of NoClassDefFoundError due to Static block Exception:







/**

 * Java program to demonstrate how failure of static initialization subsequently cause

 * java.lang.NoClassDefFoundError in Java.

 * @author Javin Paul

 */


public class NoClassDefFoundErrorDueToStaticInitFailure {



   
public static void main(String args[]){

       

        List
<User> users = new ArrayList<User>(2);

       

       
for(int i=0; i<2; i++){

           
try{

            users.
add(new User(String.valueOf(i))); //will throw NoClassDefFoundError

           
}catch(Throwable t){

                t.
printStackTrace();

           
}

       
}        

   
}

}



class User{

   
private static String USER_ID = getUserId();

   

   
public User(String id){

       
this.USER_ID = id;

   
}

   
private static String getUserId() {

       
throw new RuntimeException("UserId Not found");

   
}    

}





Output

java.lang.ExceptionInInitializerError

    at testing.NoClassDefFoundErrorDueToStaticInitFailure.main(NoClassDefFoundErrorDueToStaticInitFailure.java:23)

Caused by: java.lang.RuntimeException: UserId Not found

    at testing.User.getUserId(NoClassDefFoundErrorDueToStaticInitFailure.java:41)

    at testing.User.<clinit>(NoClassDefFoundErrorDueToStaticInitFailure.java:35)

    ... 1 more

java.lang.NoClassDefFoundError: Could not initialize class testing.User

    at testing.NoClassDefFoundErrorDueToStaticInitFailure.main(NoClassDefFoundErrorDueToStaticInitFailure.java:23)








5) Since NoClassDefFoundError is a  also a LinkageError which arises due to dependency on some other class , you can also get java.lang.NoClassDefFoundError if your program is dependent on native library and corresponding dll is not there. Remember this can also trigger java.lang.UnsatisfiedLinkError: no dll in java.library.path Exception Java. In order to solve this keep your dll along with JAR.





6) If you are using ANT build file create JAR and manifest file than its worth noting to debug till that level to ensure that ANT build script is getting correct value of classpath and appending it to manifest.mf file.





7) Permission issue on JAR file can also cause NoClassDefFoundError in Java. If you are running your Java program in multi-user operating system like Linux than you should be using  application user id for all your application resources like JAR files, libraries and configuration. If you are using shared library which is shared among multiple application which runs under different users  then you may run with permission issue , like JAR file is owned by some other user and not accessible to your application. One of our reader “it’s me said” faced java.lang.NoClassDefFoundError due to this reason. See his comment also.





8) Typo on XML Configuration can also cause NoClassDefFoundError in Java. As most of Java frameworks like Spring, Struts they all use xml configuration for specifying beans. By any chance if you put the bean name wrong, it may surface as java.lang.NoClassDefFoundError while loading other class which has dependency on wrongly named bean. This is quite common on Spring MVC framework and Apache Struts where you get tons of Exception in thread "main" java.lang.NoClassDefFoundError , while deploying your WAR or EAR file.





9) Another example of java.lang.NoClassDefFoundError as mentioned by our reader Nick is that when your compiled class which is defined in a package, doesn’t present in same package while loading like in case of JApplet it will throw NoClassDefFoundError in Java. Also see Nick’s comment on this error.





10) java.lang.NoClassDefFoundError can be caused due to multiple classloaders in J2EE environments. Since J2EE doesn’t mention standard class-loader structure and it depends upon different vendors like Tomcat, WebLogic, WebSphere on how they load different components of J2EE like WAR file or EJB-JAR file. In order to troubleshoot NoClassDefFoundError in J2EE application knowledge of How ClassLoader works in Java is mandatory. Just to recap ClasLoader works on three principle delegation, visibility and uniqueness. Delegation means every request to load a class is delegated to parent classloader, visibility means ability to found classes loaded by classloader, all child classloader can see classes loaded by parent classloader but parent classloader can not see the class loaded by child classloaders. Uniqueness enforce that class loaded by parent will never be reloaded by child clasloaders. Now suppose if a class say User is present in both WAR file and EJB-JAR file and loaded by WAR classloader which is child classloader which loads class from EJB-JAR. When a code in EJB-JAR refer to this User class, Classloader which loaded all EJB class doesn’t found that because it was loaded by WAR classloader which is child of it. 



This will result in java.lang.NoClassDefFoundError for User class. Also If class is present in both JAR file and you will call equals method to compare those two object, it will result in ClassCastException as object loaded by two different classloader can not be equal.







11) Some of reader of this blog also suggested that they get Exception in thread "main" java.lang.NoClassDefFoundError: com/sun/tools/javac/Main , this error means either your Classpath, PATH  or JAVA_HOME is not setup properly or JDK installation is not correct. which can be resolved by re-installing JDK. IF you are getting this error try to reinstall JDK . One of our reader got this issue after installing jdk1.6.0_33 and then reinstalling JDK1.6.0_25, he also has his JRE and JDK on different folder. See his comment also by searching JDK1.6.0_33 .







12) Java program can also throw java.lang.NoClassDefFoundError during linking which occurs during class loading in Java. One of the example of this scenario is just delete the User class from our static initializer failure example after compilation and they try to run the program. This time you will get java.lang.NoClassDefFoundError directly without  java.lang.ExceptionInInitializerError and message for NoClassDefFoundError is also just printing name of class as testing/User i.e. User class from testing package. Watch out for this carefully as here root cause is absent of User.class file.


java.lang.NoClassDefFoundError: testing/User

    at testing.NoClassDefFoundErrorDueToStaticInitFailure.main(NoClassDefFoundErrorDueToStaticInitFailure.java:23)








Let me know how exactly you are facing NoClassDefFoundError in Java  and I will guide you how to troubleshoot it, if you are facing with something new way than I listed above we will probably document if for benefit of others and again don’t afraid with Exception in thread "main" java.lang.NoClassDefFoundError.  








Other Exception and Error handling Tutorials from Javareivisted































Source:http://javarevisited.blogspot.com/2011/06/noclassdeffounderror-exception-in.html