Jumat, 28 Februari 2014

How to increase java heap space on Maven and ANT



Many times we get java.lang.OutOfMemoryError: java heap space while building our project either by using maven or ANT just because heap size is not enough to build the project. At this point we just want to increase the heap size used by ANT or MAVEN and this java tip will let you do this:




How to increase Java Heap size for Maven on Linux/Unix



1. Open your mvn.sh file and add the following line:

export MAVEN_OPTS=-Xmx512m

this will allow to specify java heap space based on your project needs.












How to increase Java Heap space for Maven on Windows


1.      go to C:\apache-maven-2.2.1\bin


2.      open your mvn.bat file and add the following line :


set  MAVEN_OPTS=-Xmx512m

next time you run maven commands like mvn clean or mvn install it will use this heap size.


This article is in continuation of my earlier post on java heap 10 points on java heap space  if you haven’ read that you may find some useful info there.










How to increase Java Heap size/space/memory for ANT on Linux/Unix



Similar to Maven you can specify ANT_OPTS to specify JVM specific arguments for ANT build tool. Here is step by step guide to change the java heap space for ANT:


1.      Go to ANT_HOME directry (directory where Ant has been installed)


2.      Open ant.bat file and add following line on it

export ANT_OPTS=-Xmx512m

some time you may need to put the value –Xmx512M inside double quotes.


3.      Done next time you run “ant” it will use modified java heap size and will not throw OutOfMemoryError till the new limit reached.








How to increase Java Heap size/space/memory for ANT on Windows



As shown above for Linux ANT_OPTS can also be used specify JVM specific arguments for ANT in windows.  Here is step by step guide to increase the java heap memory for ANT in Windows:


4.      Go to ANT_HOME directory (directory where Ant has been installed)

5.      Open ant.bat file and add following line on it

set ANT_OPTS=-Xmx512m

some time you may need to put the value –Xmx512M inside double quotes.

6.      Done next time you run “ant” it will use modified java heap size and will not throw OutOfMemoryError till the new limit reached.




Related post:
































Source:http://javarevisited.blogspot.com/2011/08/increase-heap-size-maven-ant.html

How to use Java 1. 7 Multiple Catch Block with example - JDK 7 tutorial



As release of JDK 7 approaching General Availability (GA) on 2011/07/28, I thought to have a look on language enhancement as part of project coin, also called as Small language enhancements or JSR 334. Though there is not any major changes like Enum or Generics of Java 1.5,  but they are still very useful, in terms of simplifying your day to day programming task. Some of the interesting changes are allowing String in Switch cases, inclusion of fork join framework in JDK itself , , type inference using diamond operator, automatic resource management using  try with resource feature, and ability to catch multiple Exception in single catch block . In this Java 7 tutorial, we will learn how multi catch block of JDK 1.7 makes Exception handling code simpler and elegant. Multiple catch block will allow you to catch multiple exceptions in one block but it’s only available in JDK7 and you need to compiler your code with source 1.7. This article also shows you how to use JDK 7 multiple catch block with example. I also recommend book Java 7 Recipes: A Problem-Solution Approach to learn more about all the changes made in JDK 1.7 and how to make effective use of them.








JDK 1. 7 feature: Improved exception handling using multi-catch block


jdk7 multi-cache block example tutorialJava has always been criticized for having checked exception and polluting code with cluttered exception handling code, multi-catch block in Java 1.7  certainly assuage those wounds. With multi catch block,  you can catch multiple exceptions in one catch block, which will eventually result in more readable code. Prior to JDK 7 if you want to catch two exceptions, you need to provide two catch blocks and if you have same code to run on these two blocks, then either you need to use finally block or just duplicate the code on two catch blocks. finally block is  not an ideal solution, because it will execute even if Exception is not thrown so ultimately lot of duplicate code which sometime makes code unreadable and clumsy. Now with JDK7 multi catch block we can catch multiple exception in one catch block separated by pipe (|) and reduce the code duplication. Let’s see an example of multiple exceptions catching in Java 7.





public static void main(String args[]) {


    Scanner scnr = new Scanner(System.in);


    String number = scnr.next();


    try {


        if (number.length() > 5) {


            throw new IllegalArgumentException();


        }


        Integer.parseInt(number);





    } catch (NumberFormatException | IllegalArgumentException e) {


        e.printStackTrace();


    }


}


In above code example or JDK7 multi-catch block we have used multiple catch block of JDK 1.7 and control will come on this block whenever code throws either NumberFormatException or IllegalArgumentException.






Java 7  multiple catch block example tutorial


We have seen code making use of this new Java 7 feature of catching more than one Exception in one catch block. In our example, we are catching NumberFormatException and IllegalArgumentException together and her we will verify that by entering input which will result in both type of Exception one by one. If we are able to catch both Exception than it's proven.


Testing of JDK 1.7 multi-cache block  



If we will enter any number with alphabets, than it will throw NumberFormatException as shown below :




Input: 23ff


java.lang.NumberFormatException: For input string: "23ff"

        at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)

        at java.lang.Integer.parseInt(Integer.java:492)

        at java.lang.Integer.parseInt(Integer.java:527)

        at jdk7demo.JDK7Demo.main(JDK7Demo.java:25)






Now let's enter number with more than 5 digit this will result in IllegalArgumentException as per our code.



Input :123333

java.lang.IllegalArgumentException

        at jdk7demo.JDK7Demo.main(JDK7Demo.java:23)


      

I used Netbeans 7 to compile and run this project. Setting up JDK 7 in Netbeans is very easy just download JDK7 and then click on Tool-->Java Platform and then click "Add Platforms" it will open a file browser just point out JDK7 installation directory and it will import JDK 1.7  binaries , source and docs and set it up for your use. One more thing you need to remember is that setting source as 1.7 because this new language feature is only available in JDK7. In next series of this JDK7 feature article we will see how to use String in Switch statement.





Recommended Book for further Reading

Java 7 Recipes: A Problem-Solution Approach By Josh Juneau, Carl Dea, Freddy Guime, John O'Conner































Source:http://javarevisited.blogspot.com/2011/07/jdk7-multi-cache-block-example-tutorial.html

Top 15 Java Multithreading, Concurrency Interview Questions Answers asked in Investment banks




Thread interview questions Java


Multi-threading and concurrency questions are essential part of any Java interview. If you are going for any Java interview on any Investment bank for equities front office position expect lots of muti-threading interview questions on your way. Multi-threading and concurrency is a favorite topics on Investment banking specially on electronic trading development and they grill candidate on many confusing java thread interview questions. They just want to ensure that the guy has solid knowledge of multi-threading and concurrent programming in Java  because most of them are in business of performance. High volume and low latency Electronic trading System which is used for Direct to Market (DMA) trading is usually concurrent in nature. These are my favorite thread interview questions on Java  asked on different on different time. I am not providing answer of these thread interview questions but I will give you hint whenever possible, some time hint is enough to answer. I will update the post further with detailed answers just like I did for 10 Singleton interview questions in Java recently.  With introduction of concurrency package in Java 5 questions on concurrent utility and concurrent collections are on rise as well. ThreadLocal, BlockingQueue, Counting Semaphore and ConcurrentHashMap are popular among those.




 


15 Java Thread Interview Questions and answers



1) You have thread T1, T2 and T3, how will you ensure that thread T2 run after T1 and thread T3 run after T2?


This thread interview questions is mostly asked in first round or phone screening round of interview and purpose of this multi-threading question is to check whether candidate is familiar with concept of "join" method or not. Answer of this multi-threading questions is simple it can be achieved by using join method of Thread class.








2) What is the advantage of new Lock interface over synchronized block in Java? You need to implement a high performance cache which allows multiple reader but single writer to keep the integrity how will you implement it?


The major advantage of lock interfaces on multi-threaded and concurrent programming is they provide two separate lock for reading and writing which enables you to write high performance data structure like ConcurrentHashMap and conditional blocking. This java threads interview question is getting increasingly popular and more and more follow-up questions come based upon answer of interviewee. I would strongly suggest reading Locks before appearing for any java multi-threading interview because now days Its  heavily used to build cache for electronic trading system on client and exchange connectivity space.








3) What are differences between wait and sleep method in java?


Another frequently asked thread interview question in Java mostly appear in phone interview. Only major difference is wait release the lock or monitor while sleep doesn't release any lock or monitor while waiting. Wait is used for inter-thread communication while sleep is used to introduce pause on execution. See my post wait vs sleep in Java for more differences








4) Write code to implement blocking queue in Java?


This is relatively tough java multi-threading interview question which servers many purpose, it checks whether candidate can actually write Java code using thread or not, it sees how good candidate is on understanding concurrent scenarios and you can ask lot of follow-up question based upon his code. If he uses wait() and notify() method to implement blocking queue, Once interviewee successfully writes it  you can ask him to write it again using new java 5 concurrent classes etc.








5) Write code to solve the Produce consumer problem in Java?


Similar to above questions on thread but more classic in nature, some time interviewer ask follow up questions How do you solve producer consumer problem in Java, well it can be solved in multiple way, I have shared one way to solve producer consumer problem using BlockingQueue in Java , so be prepare for surprises. Some time they even ask to implement solution of dining philosopher problem as well.





6) Write a program which will result in deadlock? How will you fix deadlock in Java?


Java thread interview questions and answers This is my favorite java thread interview question because even though deadlock is quite common while writing multi-threaded concurrent program many candidates not able to write deadlock free code and they simply struggle. Just ask them you have n resources and n thread and to complete an operation you require all resources. Here n can be replace with 2 for simplest case and higher number to make question more intimidating. see  How to avoid deadlock in java  for more information on deadlock in Java.








7) What is atomic operation? What are atomic operations in Java?


Simple java thread interview questions, another follow-up is do you need to synchronized an atomic operation? :) You can read more about java synchronization here.








8) What is volatile keyword in Java? How to use it? How is it different from synchronized method in Java?


Thread questions based on volatile keyword in Java has become more popular after changes made on it on Java 5 and Java memory model. It’s good to prepare well about how volatile variables ensures visibility, ordering and consistency in concurrent environment.








9) What is race condition? How will you find and solve race condition?


Another multi-threading question in Java which appear mostly on senior level interviews. Most interviewer grill on recent race condition you have faced and how did you solve it and some time they will write sample code and ask you detect race condition. See my post on Race condition in Java for more information. In my opinion this is one of the best java thread interview question and can really test the candidate's experience on solving race condition or writing code which is free of data race or any other race condition. Best book to get mastery of this topic is "Concurrency practices in Java'".








10) How will you take thread dump in Java? How will you analyze Thread dump?


In UNIX you can use kill -3 and then thread dump will print on log on windows you can use "CTRL+Break". Rather simple and focus thread interview question but can get tricky if he ask how you analyze it. Thread dump can be useful to analyze deadlock situations as well.








11) Why we call start() method which in turns calls run() method, why not we directly call run() method ?


Another classic java multi-threading interview question This was my original doubt when I started programming in thread. Now days mostly asked in phone interview or first round of interview at mid and junior level java interviews. Answer to this question is that, when you call start() method it creates new Thread and execute code declared in run() while directly calling run() method doesn’t create any new thread and execute code on same calling thread. Read my post Difference between start and run method in Thread for more details.








12) How will you awake a blocked thread in java?


This is tricky question on threading, blocking can result on many ways, if thread is blocked on IO then I don't think there is a way to interrupt the thread, let me know if there is any, on the other hand if thread is blocked due to result of calling wait(), sleep() or join() method you can interrupt the thread and it will awake by throwing InterruptedException. See my post How to deal with blocking methods in Java for more information on handling blocked thread.











13) What is difference between CyclicBarriar and CountdownLatch in Java ?


New java thread interview questions mostly to check familiarity with JDK 5 concurrent packages. One difference is that you can reuse CyclicBarrier once barrier is broken but you can not reuse ContdownLatch.








14) What is immutable object? How does it help on writing concurrent application?


Another classic interview questions on multi-threading, not directly related to thread but indirectly helps a lot. This java interview question can become more tricky if ask you to write an immutable class or ask you Why String is immutable in Java as follow-up.








15) What are some common problems you have faced in multi-threading environment? How did you resolve it?


Memory-interference, race conditions, deadlock, live lock and starvation are example of some problems comes in multi-threading and concurrent programming. There is no end of problem if you get it wrong and they will be hard to detect and debug. This is mostly experienced based interview question on java thread instead of fact based.





These were my favorite Java thread interview questions and mostly asked on Investment banks. This list is by no means complete so please contribute some of interesting java thread questions you have faced during interview. Purpose of this article is to collect and share great interview questions on multi-threading concept which not only helps on interview but opens door for learning new threading concept.





Update:


One of Javarevisited reader, Hemant has contributed some more thread interview questions in Java, though he hasn’t provide answer and left that job for me, I will certainly do when time allows, just like I have recently updated 10 Singleton interview question in Java with answers. If you guys know answers of this java concurrency questions than please post as comment:





Here is his comment “Good questions on multi-threading though you may need to prepare more in order to clear any multi-threading interview, you need to be familiar with concept of immutability, thread-safety, race condition and many more. 10 or 15 question is good for quick recap but you at-least need to prepare more than 50 questions on threading and concurrency to perform better on Java interview. You can find some interesting thread question below which is no doubt highly popular –





1)  Difference between green thread and native thread in Java?


2)  Difference between thread and process?


3)  What is context switching in multi-threading?


4)  Difference between deadlock and livelock, deadlock and starvation?


5)  What thread-scheduling algorithm is used in Java?


6)  What is thread-scheduler in Java?


7)  How do you handle un-handled exception in thread?


8)  What is thread-group, why its advised not to use thread-group in Java?


9)  Why Executor framework is better than creating and managing thread by application ?


10) Difference between Executor and Executors in Java?


10) How to find which thread is taking maximum cpu in windows and Linux server?





Apart from practicing these question answers, more important is to understand the concept behind these multi-threading questions simply mugging the answers of these thread interview questions is not going to help because there would be a lot of follow-ups based upon your answer and if you haven't master the particular thread topic it would be difficult to answer them.





Related post:






























Source:http://javarevisited.blogspot.com/2011/07/java-multi-threading-interview.html

Difference between ClassNotFoundException vs NoClassDefFoundError in Java



ClassNotFoundException vs NoClassDefFoundError

Though both of these errors are related to missing classes in classpath, main difference between them is in their root cause. ClassNotFoundExcpetion comes when you try to load a class at runtime by using Class.forName() or loadClass() and requested class is not present in classpath for example when you try to load MySQL or Oracle driver class and their JAR is not availabe, while in case of NoClassDefFoundError requested class was present at compile time but not available at runtime. Some time due to exception during class initialization e.g. exception from static block causes NoClassDefFoundError, when failed-to-load class was later referenced by runtime. From last few weeks I have been facing a cluster of ClassNotFoundException and NoClassDefFoundError while setting up a new project in Java. This new Java project has lots of dependency on various jars and some of the jar even contains the same name of file which makes my problem even more problematic. While working with NoClassDefFoundError and ClassNotFoundException I thought to document my experience and I have already shared some on 3 ways to resolve NoClassDefFoundError in Java and how to resolve ClassNotFoundException in Java. in this article though focus will be on similarity and differences between java.lang.ClassNotFoundException and java.lang.NoClassDefFoundError in Java.






NoClassDefFoundError vs ClassNotFoundException



Difference between ClassNotFoundException and NoClassDefFoundError in Java

Before seeing the differences between ClassNotFoundException and NoClassDefFoundError let's see some similarities which are main reason of confusion between these two errors:



1) Both NoClassDefFoundError and ClassNotFoundException are related to unavailability of a class at run-time.



2) Both ClassNotFoundException and NoClassDefFoundError are related to Java classpath.





Now let's see the difference between NoClassDefFoundError and ClassNotFoundException :



1) ClassNotFoundException comes in java if we try to load a class at run-time using with Class.forName() or ClassLoader.loadClass() or ClassLoader.findSystemClass() method and requested class is not available in Java. the most of the time it looks like that we have the class in classpath but eventually it turns out to be issue related to classpath and application may not be using classpath what we think it was using e.g. classpath defined in jar's manifest file will take precedence over CLASSPATH or -cp option, for more details see How Classpath works in Java. On the other hand NoClassDefFoundError is little different than ClassNotFoundException, in this case culprit class was present during compile time and let's application to compile successfully and linked successfully but not available during run-time due to various reason.



2) ClassNotFoundException is a checked Exception derived directly from java.lang.Exception class and you need to provide explicit handling for it while NoClassDefFoundError is an Error derived from LinkageError.



3) If you are using ClassLoader in Java and have two class loaders then if a ClassLoader tries to access a class which is loaded by another classloader will result in ClassNoFoundException.



4) ClassNotFoundException comes up when there is an explicit loading of class is involved by providing name of class at runtime using ClassLoader.loadClass(), Class.forName(),  while NoClassDefFoundError is a result of implicit loading of class because of a method call from that class or any variable access.



Please let us know if you are aware of any other difference between NoClassDefFoundError and ClassNotFoundException in Java , I would be happy to incorporate those.



Related post :

How to resolve NoClassDefFoundError in Java

How HashMap works in Java?

How Garbage Collection works in Java?

Why String is immutable in Java?

10 practical tips on Java debugging with eclipse

How Synchronization works in Java?

How Classpath works in Java?























Source:http://javarevisited.blogspot.com/2011/07/classnotfoundexception-vs.html

Kamis, 27 Februari 2014

Why multiple inheritances are not supported in Java



Why multiple inheritence is not supported implemented in javaRecently one of my friend appeared for an interview and after few so called easy questions he was asked "Why multiple inheritance is not supported in Java" , though he has a brief idea that in Java we can support multiple inheritance in java via interface but interviewer was keep pressing on why part , may be he was just read any blog post about it :). So after the interview my friend comes to me and in usual talk he told me about this questions and ask me the answer. Well this is very classical question like Why String is immutable in Java; similarity between these two questions is they are mainly driven by design decision taken by java's creator or designer. Though following two reason make sense to me on Why Java doesn't support multiple inheritances:






Why Java doesn't support multiple inheritance


1) First reason is ambiguity around Diamond problem, consider a class A has foo() method and then B and C derived from A and has there own foo() implementation and now class D derive from B and C using multiple inheritance and if we refer just foo() compiler will not be able to decide which foo() it should invoke. This is also called Diamond problem because structure on this inheritance scenario is similar to 4 edge diamond, see below



           A foo()

           / \

          /   \

   foo() B     C foo()

          \   /

           \ /

            D

           foo()



In my opinion even if we remove the top head of diamond class A and allow multiple inheritances we will see this problem of ambiguity.



Some times if you give this reason to interviewer he asks if C++ can support multiple inheritance than why not Java. hmmmmm in that case I would try to explain him the second reason which I have given below that its not because of technical difficulty but more to maintainable and clearer design was driving factor though this can only be confirmed by any of java designer and we can just speculate. Wikipedia link has some good explanation on how different language address problem arises due to diamond problem while using multiple inheritances.



2) Second and more convincing reason to me is that multiple inheritances does complicate the design and creates problem during casting, constructor chaining etc and given that there are not many scenario on which you need multiple inheritance its wise decision to omit it for the sake of simplicity. Also java avoids this ambiguity by supporting single inheritance with interfaces. Since interface only have method declaration and doesn't provide any implementation there will only be just one implementation of specific method hence there would not be any ambiguity.








Related post:



































Source:http://javarevisited.blogspot.com/2011/07/why-multiple-inheritances-are-not.html

String vs StringBuffer vs StringBuilder in Java




Difference between String, Stringbuffer and StringBuilder


String is one of the most important classes in Java and anyone who starts with Java programming uses String to print something on console by using famous System.out.println() statements. Many Java beginners not aware that String is immutable and final in Java and every modification in String result creates a new String object. So How do you manipulate String in Java without creating String garbage? StringBuilder and StringBuffer is answer of this question. StringBuffer is old class but StringBuilder is newly added in Java 5 along with major improvements like Enum, Generics, varargs methods and Autoboxing in Java. No matter which kind of application you are working you will find heavy usage of Java String class but if you do profiling of your application you will find that String is the one class which creates lots of garbage because of many temporary String created in program. In this Java tutorial we will see What is String in Java, some important properties of String in Java, What is StringBuffer in Java , When to use StringBuffer in Java , StringBuilder in Java and how it can be used in place of StringBuffer,  What are differences between String and StringBuffer and StringBuilder in Java  which is a frequently asked core Java question and mostly String vs StringBuilder vs StringBuffer. Now let's start with String.






Differences between String, StringBuffer and StringBuilder in Java



String in Java


Before looking difference between String and StringBuffer or StringBuilder let’s see some fundamental properties of String Class in Java



string and stringbuffer, string vs stringbuffer vs stringbuilder1) String is immutable in Java:  String is by design immutable in Java you can check this post for reason. Immutability offers lot of benefit to the String class e.g. his hashcode value can be cached which makes it a faster hashmap key and one of the reason why String is a popular key in HashMap. Because String is final it can be safely shared between multiple threads  without any extra synchronization.



2)when we represent string in double quotes like "abcd" they are referred as String literal and String literals are created in String pools. When you compare two String literals using equality operator "==" it returns true because they are actually same instance of String. Anyway comparing object with equality operator is bad practice in Java and you should always use equals method to check equality.



3) "+" operator is overloaded for String and used to concatenated two string. Internally "+" operation is implemented using either StringBuffer or StringBuilder.



4) Strings are backed up by character Array and represented in UTF-16 format. By the way this behavior can cause memory leak in String because same character array is shared between source String and SubString which can prevent source String from being garbage collected. See How SubString works in Java for more details.



5) String class overrides equals() and hashcode() method and two Strings are considered to be equal if they contain exactly same character in same order and in same case. If you want ignore case comparison of two strings consider using equalsIgnoreCase() method. See  how to correctly override equals method in Java  to learn more about best practices on equals method. Another worth noting point is that equals method must be consistent with compareTo() method for String because SortedSet and SortedMap e.g. TreeMap uses compareTo method to compare String in Java.



7) toString() method provides String representation of any object and its declared in Object class and its recommended for other class to implement this and provide String representation.



8) String is represented using UTF-16 format in Java.



9) In Java you can create String from char array, byte array, another string, from StringBuffer or from StringBuilder. Java String class provides constructor for all of these.






Problem with String in Java


difference between String and StringBuffer and StringBuilder, string vs stringbuffer One of its biggest strength Immutability is also biggest problem of Java String if not used correctly. many a times we create a String and then perform a lot of operation on them e.g. converting string into uppercase, lowercase , getting substring out of it , concatenating with other string etc. Since String is an immutable class every time a new String is created and older one is discarded which creates lots of temporary garbage in heap. If String are created using String literal they remain in String pool. To resolve this problem Java provides us two Classes StringBuffer and StringBuilder. String Buffer is an older class but StringBuilder is relatively new and added in JDK 5.






Differences between String and StringBuffer in Java


Main difference between String and StringBuffer is String is immutable while StringBuffer is mutable means you can modify a StringBuffer object once you created it without creating any new object. This mutable property makes StringBuffer an ideal choice for dealing with Strings in Java. You can convert a StringBuffer into String by its toString() method. String vs StringBuffer or what is difference between StringBuffer and String is one of the popular Java interview questions for either phone interview or first round. Now days they also include StringBuilder and ask String vs StringBuffer vs StringBuilder. So be preparing for that. In the next section we will see difference between StringBuffer and StringBuilder in Java.




Difference between StringBuilder and StringBuffer in Java



StringBuffer is very good with mutable String but it has one disadvantage all its public methods are synchronized which makes it thread-safe but same time slow. In JDK 5 they provided similar class called StringBuilder in Java which is a copy of StringBuffer but without synchronization. Try to use StringBuilder whenever possible it performs better in most of cases than StringBuffer class. You can also use "+" for concatenating two string because "+" operation is internal implemented using either StringBuffer or StringBuilder in Java. If you see StringBuilder vs StringBuffer you will find that they are exactly similar and all API methods applicable to StringBuffer are also applicable to StringBuilder in Java. On the other hand String vs StringBuffer is completely different and there API is also completely different, same is true for StringBuilder vs String.




Summary



In summary here are list of difference between StringBuffer, String and StringBuilder in Java :





1) String is immutable while StringBuffer and StringBuilder is mutable object.


2) StringBuffer is synchronized while StringBuilder is not which makes StringBuilder faster than StringBuffer.


3) Concatenation operator "+" is internal implemented using either StringBuffer or StringBuilder.


4) Use String if you require immutability, use Stringbuffer in java if you need mutable + thread-safety and use StringBuilder in Java if you require mutable + without thread-safety.





That's all on famous String vs StringBuffer or StringBuffer vs StringBuilder discussion. All these differences helps to avoid common coding mistake of using String in place of StringBuffer in many places. from Java 5 onwards either use + operator of StringBuilder for concatenating String in Java. 






Other Java String tutorials from Javarevisited Blog




How to Split String in Java with Example




How to convert String to Integer in Java























Source:http://javarevisited.blogspot.com/2011/07/string-vs-stringbuffer-vs-stringbuilder.html

10 Tips to Debug Java Program in Eclipse




How to debug java program in Eclipse


Debugging is a must have skill for any java developer. Having ability to debug java program enables to find you any subtle bug which is not visible during code review or comes when a particular condition offer, This becomes even more important if you are working in high frequency trading or electronic trading system project where time to fix a bug is very less and bug usually comes on production environment and doesn't appear in your Windows XP machine. in my experience debugging java application also helps you understand flow of java program. In this java tutorial we will see how to debug a java program, setting up remote debugging in java and some java debugging tips on Eclipse and Netbeans IDE. It’s also good to know various java debug tool available and how java debugger or jdb works but it’s not mandatory for doing debugging in Java. To start java debugging you just needs your project to be configured in a modern IDE like eclipse and Netbeans and you are ready to debug java program.








Java debugging tools


Java debugging tutorial example, java debugger, java debugging tools and tipsI mostly used Eclipse IDE and Netbeans IDE for java development and these IDE have great support for java debugging. They allow you to set various breakpoints like line breakpoint, conditional breakpoints or exception breakpoint. I prefer Eclipse over netbeans because of its seamless integration with remote debugging because most of the time your application will run on Linux machine and you might not have local version running on your machine, in such scenario remote debugging is extremely useful. You can check how to setup java remote debugging in eclipse for step by step guide on setting remote debugging in eclipses. Apart from Eclipse and Netbeans IDE you can also use Java debugger jdb which is a simple command line based java debugger and based on java platform debugging architecture and can be used to debug java program locally or remotely.




Java debug options


If you are not using any IDE for java debugging locally you need to provide java debug option while starting your program. You need to provide java debug option also if you are setting up remote debugging session or using jdb for java debugging. Following are the two java debugging option which needs to be provided to java program:





Debug Options Purpose
Xdebug         Used to run java program in debug mode
Xrunjdwp:transport=dt_socket,server=y,suspend=n        Loads in Process debugging libraries and specifies the kind of connection to be made.

Suspend=y and n is quite useful for debugging from start or debugging at any point.




Using jdb to debug java application


1) Start your java program with two options provided above for example, below command will start StockTrading java program in debug mode.



 % java -Xdebug -Xrunjdwp:transport=dt_socket,address=8000,server=y,suspend=n StockTrading



After starting your java application in debug mode you can attach java debugger "jdb" to the VM with the following command:



 % jdb -attach 8000



You can check the jdb manual page for complete detail on how to do java debugging with jdb.




Java remote debugging with eclipse


This is another cool feature of eclipse which allows you to connect your java application running on remote host and do remote debugging. You just need to start your java application with the java debug option discussed above and then connect your application from eclipse into specified port. You can check below link for step by step guide on java remote debugging with eclipse.






Debugging Java Program in Eclipse and Netbeans


Debugging java application locally on any IDE like Eclipse or Netbeans it’s very simple, just select the project and click debug or use debug shortcut provided by IDE. You can also debug a single java class with main method. In Eclipse just right click and select "Debug as Java Application".




10 practical Java debugging tips


Now let's see some java debugging tips which I used while doing debugging in Java in eclipse.



1) Use conditional breakpoint

Eclipse allows you to setup conditional break point for debugging java program, which is a breakpoint with condition and your thread will only stop at specified line if condition matches instead of just stopping on that line like in case of line breakpoint. To setup a conditional breakpoint just double click on any line where you want to setup a breakpoint and then right click --> properties and then insert the condition. Now program will only stop when that particular condition is true and program is running on debug mode.




java debugging tutorial and tips




debugging in java and eclipse tips







2) Use Exception breakpoint

How many times you have frustrated with a NullPointerException and you don't know the source from where the exception is coming. Exception breakpoints are just made for such situation. Both Eclipse and Netbeans allows you to setup Exception breakpoint. You can setup Exception breakpoint based on java exception like NullPointerException or ArrayIndexOutOfBoundException. You can setup Exception breakpoint from breakpoint window and your program will stop when you start it on debug mode and exception occurs.




how to debug java program in eclipse

3) Step over, Step Into

These are simply great debugging options available in any Java IDE, extremely useful if you are debugging multi-threaded application and want to navigate step by step.



4) Stopping for a particular Thread

This is my own custom made java debugging tips which I made using conditional breakpoints. since most of my projects are multi-threaded java programs and I want only a particular thread to stop on a particular line, for doing that I setup a conditional breakpoint on that line and put Thread.currentThread().getName().equals("TestingThread") and it works fantastically.



5) Inspect and Watch

These are two menu options which I use to see the value of expression during debugging java program. I just select the statement, right click and inspect and it will show you the value of that statement at debugging time. You can also put watch on that and that condition and its value will appear on watch window.



6) Suspending and resuming thread

You can suspend and resume any thread while debugging java program from debug window. Just right click on any thread and select either suspends or resume. This is also very useful while debugging multi-threading program and simulating race conditions.



7) Using logical structure

Logical structure option is very useful for examining contents inside java collection classes like java hasmap or Java Arraylist during java debugging. Logical view will show the contents like key and value of hashmap instead of showing full details of hashmap which we may not be interested, you can enable and disable logical view from variables window.



8) Step filtering

When we do Step Into on process debugging java program control goes form one class to other and it eventually go to JDK classes like System or String. Some time we just to remain in our application and don't want to navigate into JDK System classes in that case Step filtering is great you can just filter out JDK class from Step into. You can setup step filtering from preferences àJavaàDebugàStep Filtering and enable and disable it from Debug window.



9) Copy Stack

While debugging java program if you want to copy the stack of a thread which hit the breakpoint and suspended you do so by "Copy Stack" option. Just right click on Thread on Debug Window and select "Copy Stack".



10) Last tip is use java debugging as last option and not the first option because it’s very time consuming, especially remote java debugging which takes a lot of time if network latency is very high between local and remote host. Try to identify problem by looking at code it would be very handy and quick.



lastly java debugging is real fun so definitely try it few times to get hold of it and please share some other java debugging tips you use on your daily life.























Source:http://javarevisited.blogspot.com/2011/07/java-debugging-tutorial-example-tips.html