Count Number of Statements in a Java Method By Using Eclipse JDT ASTParser

This tutorial belongs to Eclipse JDT Tutorial Series.

Given a method, we may want a count of the number of statements in the method (for ex: to gauge the complexity of the method). We can use eclipse JDT ASTParser to get this job done.

One approximate way to count the number of statements in a method is to count the number of lines ending with the semi-colon along with lines that contain the words "if/for/while/".

In this post, I will explain one technique of counting the number of statements in a more accurate manner using the eclipse jdt visitor paradigm. This previous post is about how visitor works.

This example demonstrates the use of the visit and end-visit to capture things happening between the visit and end-visit.

Basically, we initialize a field, statement count to 0 in the visit of a method declaration, increment this field in each visit of statements such as If statement, return statement and so on. Finally, when the end visit of the method declaration is called, we have a count of the statements in the method.

public boolean visit(MethodDeclaration md) {
	// initialize the field to 0
	m_nStatementCount = 0;
	return true;
public void endVisit(MethodDeclaration md) {
	System.out.println("Statement count for method" + md.getName().getFullyQualifiedName() + 
	+ m_nStatementCount);
// the visitors below increment the statement count field
public boolean visit (ReturnStatement node) {
	return true;
public boolean visit (ExpressionStatement node) {
	return true;
public boolean visit (IfStatement node) {
	return true;
//and so on for other subclasses of Statement.*

*You have to write the above code for each of the sub-classes of Statement
described in

Note: there is no visit method that takes a Statement object as param, otherwise we could have had one such visit method where the count is incremented.

To get a whole view of how the whole method works, go to a previous post here.

Category >> Java Development Tools (JDT)  
If you want someone to read your code, please put the code inside <pre><code> and </code></pre> tags. For example:
String foo = "bar";
  • A random reader

    You saved my life buddy.

  • Admin

    Hi Sagar, thanks very much for your comments. It’s GREAT to hear from student from another country!

    This blog is mainly for tracking my research/techniques. I saw your comments before, and replied if I knew the answer. I guess the number of visitors are not large enough so that someone else can also reply and discuss the problem.

    You are more than welcome to email me for problem discussion, even though I prefer comments on my blog.


  • sagar

    Excellent explanation…A very good article . Only one complaint is there, if we have issues/doubts there is no forum on programcreek where we can get answer. Also, the questions/doubts posted here in reply, never get a reply. Please do something about it. Thanks .