Free Online Courses for Software Developers - MrBool
× Please, log in to give us a feedback. Click here to login
×

You must be logged to download. Click here to login

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

Introduction to JDB (Java Debugger)

In this article, we will talk about the Java Debugger and also how to use it in your projects in order to get more productivity at the code side.

JDB or Java Debugger is a command line utility which enables us to debug our developed java code with real time values. It provides inspection of the parameters which are used in the program. JDB tool comes with the SUN JDK. The executable library resides within /bin directory as a shell file on UNIX Platform or as an exe file on Microsoft Platform.

What is Debugging?

Debugging is a technical process which helps to find bugs and remove them within a program in an efficient manner. The process of debugging includes testing and monitoring. In a tightly coupled environment, it becomes more complicated to debug. We normally debug a program using the debugger tools which suits our environment. A debugger enables us to step through each and every aspect of the code, inspect the elements at runtime, and get rid of errors, if any.

Debugging Techniques

We have various techniques which can be used to debug a Java program. The traditional one of debugging is by putting using 'System.out.print' statements at the end of every logical segment. This will print the trace statements on the console. Let us look at the following code -

Listing 1: A Simple Java Code with 'System.out.print' statements –

pubic class Add {
   public static void main( String args [] )   {
      int num1 = args[0];
      system.out.println( " Number 1 : " + num1 );
      int num2 = args[1];
      system.out.println( " Number 2 : " + num2 );
      int num3 = a + b;
      system.out.println( " Number 3 : " + num3 );
   }
}

In this program, we have two integers and their sum is printed out. It should be noted here that at each step, we have introduced a print statement which prints the state of the program; i.e. the values of the variables on the console. This is the traditional way of debugging a program.

In addition to this, we have some advanced concepts which are used to debug a program such as:

  • stepping
  • breakpoints, and
  • exceptions or watchpoints.

Types of Debugging

We have different options to debug a program. These are listed below:

  • Using Java bytecode (compiled version of Java code)
  • Using comments inside the programs
  • Attaching a class to a running program
  • Remote debugging
  • Debugging on demand
  • Optimized code debugging

Most commonly used debuggers are listed below -

  • Common IDEs e.g. eclipse, netbeans, Jbuilder have their own inbuilt debuggers.
  • Standalone debugger GUI e.g. Java Platform Debugger, JIKES etc.
  • Command line debugger - JDB from Sun.
  • In-line debuggers; i.e using the 'System.out.print' statements.

Java Debugger or JDB

Java Debugger or JDB is a tool that helps us to debug our java code using the command line. It implements the Java Platform Debugger Interface. This tool is very helpful to detect and fix bugs in a Java Program.

JDB Architecture

JDB consists of three major components. The following diagram shows the JDB architecture

Figure 1 - The JDB Architecture

As shown in the picture, the JDB architecture consists of three major components. These are -

  • The JVM tool interface.
  • The Java Debug wiring protocol or the JDWP.
  • The Java Debugger Interface.

JVM Tool Interface

The JVM tool interface is a native programming interface which is implemented by the Virtual Machine. It has the ability to inspect and debug the state of the application which is running on the Virtual Machine. It has an implementer called VM Implementer which can be easily enclosed into the debugging architecture. It also uses a third-party communication channel called the Java Debug Wire Protocol or JDWP.

JDWP

The Java Wiring Debug Protocol defines the format of information and the requests which are passed to the debuggee process and the debugger front end. The main purpose of having this protocol is to facilitate the communication between the debuggee and the debugger when they are running under separate Virtual Machines or even on separate platforms.

JDI

The JDI is a high-level Java interface which is implemented as the front end. This defines the variable information at the user code level. It is always recommended to use the Java Debugger Interface layer for all sorts of debugger development. It uses the Java Debugger Wiring Protocol to communicate with the debuggee Java Virtual Machine.

Installing JDB

Java Debugger or JDB comes as a part of JDK. Thus Standard JDK installation should be good enough to use JDB from command prompt. The following list has the minimum system requirement to install and use JDB.

  • JDK Version - JDK 1.5 or Java SE2 or above
  • Memory Required - 1 GB (minimum)
  • Disk space - No minimum requirement
  • Operating System - Windows XP or above. RHEL.

After ensuring the above minimum requirement, let us go through the following steps to install JDB -

Step 1 - Check the Java Version

Open the command prompt on windows system or the terminal on the RHEL and simply type - 'java -version'

If java is up and running on that system, you should get the output as -

'Java version 1.X.yy.' Make sure that the version is 1.5 or higher. It is assumed that the readers of this document are well versed with Java world. In case, you need to install java, you can download and install java from the official website - http://java.com.

Step 2 - Setup the java environment

Before going into the next step, ensure that the Java Environment is set up. Open the command prompt on windows system or the terminal on the RHEL and simply type the following as per your environment -

On Windows - set the JAVA_HOME environment variable to the location where Java is installed e.g. C:\ProgramFiles\Java\Java_

On UNIX environment, use the following command - export JAVA_HOME=/usr/local/java

Step 3 - Verify the JDB installation

Verify the JDB installation as mentioned below -

Simply open the command prompt on windows system or the terminal on the RHEL and type -

'jdb -version'.

Executing the JDB Command

The JDB command consists of four sections as mentioned below -

  • JDB - This calls the JDB.exe or JDB.sh depending upon the environment
  • option - This mentions the command line options which are used to debug the given a Java program in an efficient manner. The JDB launcher accepts all the options which the java command accepts e.g. -D, -classpath, and -X. In addition to these, there are some additional advanced options e.g. -attach, -listen, -launch, etc.
  • class - This is the class name which is to be debugged.
  • arguments - These are the input parameters which the program requires at runtime.

Following is the list of options that are available to be executed with the JDB command -

  • -help This option displays the help message and lists the related options.
  • -sourcepath This option takes the given path of the source files. If the path is not specified, then it takes the default path “.”, i.e., the current directory.
  • -attach This option attaches the debugger to the running VM by specifying the running VM address.
  • -listen This options waits for the running VM to connect using standard connector.
  • -listenany This options waits for the running VM to connect using any address.
  • -launch This options launches the debugged application immediately up on startup job.
  • -listconnectors This options lists the connectors available in this VM.
  • -connect This options connects to the target VM using named connector with listed argument values.
  • -dbgtrace This options prints information for debugging jdb.
  • -tclient This options runs the application in Java Hotspot VM (client).
  • -tserver This options runs the application in Java Hotspot VM (server).
  • -Joption This options passes the option to the Java virtual machine used to run JDB.

JDB Session

We can launch the JDB session following either of the two methods listed below -

  • Start the JDB session by adding the main class.
  • Include the JDB into a running JVM to start the session.

Start the JDB session by adding the main class. We can start the JDB session by executing the following command from the command prompt -

jdb <CLASSNAME>

This command starts a new Java Virtual Machine Session with the parameters that are specified. Once the session is started, it loads the class and stops before executing the first statement of the class.

Include the JDB into a running JVM to start the session- We can include the JDB into a running Java Virtual Machine by executing the following command -

java -agentlib:jdwp=transport=dt_shmem,address=jdbconn,server=y,suspend=n <CLASSNAME>

Once this is executed, we need to attach the JDB to the JVM using the following command -

jdb -attach jdbconn

Consider the following class -

Listing 2: A Simple Java class to illustrate java debugger -

  public class TestDebuggerClass {
   
         private int num1 ;
         private int num2 ;
   
         public TestDebuggerClass ( int a, int b ) {
               num1 = a ;
               num2 = b ;
         }
   
         public static void main ( String[] args ) {
               System.out
                             .println( " Hi, I am within the main method .... and I am going to call the functions " ) ;
               function1() ;
               function2(3, 4) ;
               function3(4, 5) ;
               function4() ;
               function5() ;
         }
   
         public static void function1 () {
               System.out.println ( " I am function 1 ... " ) ;
               System.out.println ( " I am still function 1 ... " ) ;
               System.out.println ( " I am still function 1 ... " ) ;
         }
   
         public static int function2 ( int a, int b ) {
               return a + b ;
         }
   
         public static TestDebuggerClass function3 ( int a, int b ) {
               TestDebuggerClass obj = new TestDebuggerClass (a, b) ;
               obj.reset() ;
               return obj ;
         }
   
         public static void function4 () {
               System.out.println( " I am in function 4 ... " ) ;
         }
   
         public static void function5 () {
               TestDebuggerClass testObj = new TestDebuggerClass(5, 6) ;
   
               synchronized (testObj) {
                      System.out.println ( " I am in f5, accessing the  Class's fields " + testObj.num1 + " " + testObj.num2) ;
               }
         }
   
         private void reset () {
               num1 = 0 ;
               num2 = 0 ;
         }
   
  }
  

Compile this class as under -

E:\Utpal\Work\HomeWorkspace\JavaDebuggerProject\src>javac
-d E:\Utpal\Work\HomeWorkspace\JavaDebuggerProject\bin TestDebuggerClass.java

After compilation, check the bin directory to see if the class file is generated there or not. Now from the bin directory, run the following command -

jdb TestDebuggerClass

On executing this, you should get the following output -

Initializing jdb ...
  >

On the > prompt simply type - 'run' and you will get the following output -

run TestDebuggerClass
  Set uncaught java.lang.Throwable
  Set deferred uncaught java.lang.Throwable
  >
  VM Started: Hi, I am within the main method .... and I am going to call the functions
  I am function 1 ...
  I am still function 1 ...
  I am still function 1 ...
  I am function 4 ...
  I'm function5, accessing Class's fields 5, 6
The application exited

Using the breakpoints

Now, let’s see how we use the breakpoints. A breakpoint introduces an explicit stop or pause in the execution of a program at a particular line in the program. It is very helpful while debugging to check the status of the variables. The syntax of this command is as under -

> stop at : <class name>:<Line no>

Debugging mechanism is carried out in the following steps. Let us use the same java code which we used earlier –

Step 1 - Start the JDB session

The following command is used to start the JDB session on the TestDebuggerClass class for debugging:

\> jdb TestDebuggerClass


Step 2 - Set a Breakpoint

The following is used to set up a breakpoint on the main() method of TestDebuggerClass class.

> stop in TestDebuggerClass.main

If the breakpoint is set successfully, you should see the following output:

Deferring breakpoint TestDebuggerClass.main.
It will set after the class is loaded.
>


Step 3: Start Debugging

The following command is used to start the execution of the class TestDebuggerClass:

array13

On executing this command, you should see the following output. In the output, you will find that the execution stops at the breakpoint position, which is at the main() function. The execution halts on the first line of the main method, which is -

System.out.println ( " Hi, I am within the main method .... and I am going to call the functions " ) ; or Line no: 12 in the above code. You can check this information in the output that is produced.

Step 4: Continue Execution

The following command is used to continue the program execution:

> cont

Now, this gives you the remaining execution part and output as under:

> TestDebuggerClass:12
  The application exited
  \>

Complete execution of this is shown as under -

E:\Utpal\Work\HomeWorkspace\JavaDebuggerProject\bin>jdb TestDebuggerClass
  Initializing jdb ...
  > stop in TestDebuggerClass.main
  Deferring breakpoint TestDebuggerClass.main.
  It will be set after the class is loaded.
  > run TestDebuggerClass
  run TestDebuggerClass
  Set uncaught java.lang.Throwable
  Set deferred uncaught java.lang.Throwable
  >
  VM Started: Set deferred breakpoint TestDebuggerClass.main
  
Breakpoint hit: "thread=main", TestDebuggerClass.main(), line=12 bci=0

main[1] cont
> Hi, I am within the main method .... and I am going to call the functions
I am function 1 ...
  I am still function 1 ...
  I am still function 1 ...
  I am function 4 ...
  I'm function5, accessing Class's fields 5, 6
  The application exited

Stepping

In this section, we will see how to use the concept of Stepping while debugging a program. Stepping is an important debugging feature which allows us to execute the code by putting our steps through line by line. Using this, you can examine each line of the code to ensure they are behaving as intended.

The following commands are used in the stepping process:

step: steps to the next line of execution
  list: examines where you are in the code
  cont: continues the remaining execution

Let us consider that a breakpoint is set on the main() method of the TestDebuggerClass class. The following steps will show how to apply the stepping in the TestDebuggerClass class.

Step 1: Execute the Job

The following command is used to start execution of the class - TestDebuggerClass.

array13

On executing this command, you will see the following output. In this output, you will see that the execution stops at the breakpoint position, which is the main() method of the code.

The execution stops at the first line of the main method which is as under -

System.out.println ( " Hi, I am within the main method .... and I am going to call the functions " ) ; or Line no: 12 in the above code.

Step 2: Step through the Code

The following command is used to step in the execution to the next line and you should get the following output -

E:\Utpal\Work\HomeWorkspace\JavaDebuggerProject\bin>jdb TestDebuggerClass
  Initializing jdb ...
  > stop in TestDebuggerClass.main
  Deferring breakpoint TestDebuggerClass.main.
  It will be set after the class is loaded.
  > run TestDebuggerClass
  run TestDebuggerClass
  Set uncaught java.lang.Throwable
  Set deferred uncaught java.lang.Throwable
  >
  VM Started: Set deferred breakpoint TestDebuggerClass.main
  Breakpoint hit: "thread=main", TestDebuggerClass.main(), line=12 bci=0

Step 3: List the Code

The following command is used to list the code:

main[1] list

You get the following output. List command is used to show the line in the code up to which the program control has reached. Notice the arrow mark => in the following actually shows the current position of the program control -

8 num2 = b;
  9 }
  10
  11 public static void main(String[] args) {
  12 => System.out
  13 .println(" Hi, I am within the main method .... and I am going to call the functions ");
  
  14 function1();
  15 function2(3, 4);
  16 function3(4, 5);
  17 function4();

Step 4: Continue Execution

The following command continues to execute the code:

array23

This command continues executing the remaining lines of the code. The output is as shown below:

array23

> Hi, I am within the main method .... and I am going to call the functions

I am function 1 ...
  I am still function 1 ...
  I am still function 1 ...
  I am function 4 ...
  I'm function5, accessing Class's fields 5 6
  
  The application exited

Stepping types -

Generally, we have three types of stepping:

  • Step Into
  • Step Over
  • Step Out

Step Into

Step into command is used to step to the next line of the code. If there is a function call in the next line of the code, it then enters into the function by setting the control at the first line of the function. If we use the step into command, the controller moves to the next line. functionf1(). At this line, there is a function call functionf1() and hence the controller moves to the topmost line of the addition function with the arrow mark.

Step Over

Step Over is used to execute the next line. But if the next line is a function call, it executes that function in the background and returns the result. Let us take an example. In the following code, the arrow mark defines the control in the code. If you use the step over command, the control moves to the next line, i.e., function1(). On this line, there is a function call function1() and hence the function execution is done in the background and the result is returned to the current line along with the arrow mark.

Step Out

The Step Out command executes the next line. If the next line is a function call, it skips that line and the function execution continues normally with the remaining lines of the code. Let us see this in the example. In the above code, the arrow mark defines the controller in the code. If we use the step out command here, the controller then moves to the next line, i.e., function1(). On this line, we have a function call function1() and hence the function execution is skipped while the remaining execution continues with along with the arrow mark.

Exception Handling in JDB

Now let us talk about the exception handling part in JDB. Usually, when a program raises an exception without having a catch statement, then it becomes the responsibility of the VM to print the exception, its cause, and then exit the program. If in the program, thenwe have an appropriate catch block then it becomes the responsibility of the catch block to take up all these jobs. It hasbeenraised with a catch statement, then the exception is handled by the catch statement. Here, the VM prints the output with the cause of exception.

When the class that raises the exception is running under JDB, it also throws the uncaught exception. That exception can be handled using the catch command.

Let us consider the following class -

Listing 3: A Simple Java class to illustrate JDB Exception handling -

public class JdbException {
   public static void main(String ar[]) throws Exception {
      int x = 78, y = 0;
      System.out.println(" Welcome to JDBException Class" );
      System.out.println(" The exception is : " + (x/y) );
   }
}

Once compiled, go thru the following steps.

Step 1: Run the Class

Run this class as under -

\>jdb JdbException
>run

You should get the following outout -

Initializing jdb ...
> run
run JdbException
Set uncaught java.lang.Throwable
Set deferred uncaught java.lang.Throwable
> 
VM Started:  Welcome to JDBException Class
 
Exception occurred: java.lang.ArithmeticException (uncaught)"thread=main", JdbException.main(), line=5 bci=30
5          System.out.println(" The exception is : " + (x/y) );
 
main[1]

Step 2: Catch the Exception

Catch the arithmetic exception by using the following command -

mian[1] catch java.lang.ArithmeticException

You should get the following output -

Set all java.lang.ArithmeticException

Step 3: Continue the Execution

Use the following command to continue the exception -

array23

You should get the following output -

> Exception in thread "main" java.lang.ArithmeticException: / by zero
        at JdbException.main(JdbException.java:5)
                                                                                      
The application exited

Conclusion

Through this document, I have tried to cover the different aspects of JDB or the Java debugger. Let us conclude this article in following bullets -

  • JDB or Java Debugger is a command line utility which enables us to debug our developed java code with real time values.
  • Java Debugger or JDB comes as a part of JDK.
  • Java Debugger or the JDB runs in the following steps -
    • Create the JDB session.
    • Use the breakpoints.
    • Use the stepping options.
    • Handle the exceptions, if any.

I hope by now you have got a good idea of JDB or Java Debugger and also hope that you have enjoyed reading this document.



Website: www.techalpine.com Have 16 years of experience as a technical architect and software consultant in enterprise application and product development. Have interest in new technology and innovation area along with technical...

What did you think of this post?
Services
[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login