MYHOSPITALNOW.COM

Find Trusted Doctors & Hospitals

Discover healthcare providers, compare hospitals, and explore treatment options worldwide.

Free Treatment Quotes • Doctor Search • Hospital Comparison

Find Healthcare Options

www.myhospitalnow.com

Groovy Tutorials: How to write comments in Groovy?

Groovy has three kinds of comment that it shares with Java: single-line comments with //, block comments between /* and */, and GroovyDoc comments between /** and */. Groovy scripts can also start with a shebang line. This page shows each form with examples, then covers the mistakes people make most often (nested block comments, # comments, comment markers inside strings), how comments behave in Jenkinsfiles, and how to turn GroovyDoc comments into HTML documentation.

Single-Line Comments

Single-line comments start with // and extend to the end of the line. They are typically used for brief explanations or notes.


// This is a single-line comment
println("Hello, World!") // This prints a message to the consoleCode language: JavaScript (javascript)

Multiline Comments


Multiline comments, also known as block comments, begin with /* and end with */. They can span multiple lines and are useful for providing detailed explanations or documentation.


/*
  This is a multiline comment in Groovy.
  It can span multiple lines and is useful
  for documenting complex logic or providing
  detailed explanations.
*/

// Example usage in a function:
def exampleFunction() {
    /* This is a multiline comment
       inside a function. It can explain
       what the function does or document
       important information.
    */
    println("This function does something.")
}Code language: JavaScript (javascript)

Documentation Comments

Groovy also supports documentation comments, which are a form of multiline comments used to generate documentation. These comments start with /** and end with */. They are processed by tools like GroovyDoc to create API documentation.


/**
 * This is a documentation comment.
 * It is used to describe the purpose and behavior
 * of a class, method, or field in detail.
 *
 * @param name The name of the user
 * @return A greeting message
 */
def greetUser(name) {
    return "Hello, ${name}!"
}Code language: PHP (php)

Best Practices

โ€ข   Use Comments Sparingly: Write clear and concise code that doesnโ€™t rely heavily on comments for understanding.
โ€ข   Keep Comments Updated: Ensure comments are updated along with the code changes to avoid confusion.
โ€ข   Document Public APIs: Use documentation comments to describe public methods, classes, and fields, especially in libraries and frameworks.Code language: JavaScript (javascript)


Groovy comment types at a glance

The examples above show the three main comment styles. The table below lists all four comment forms Groovy recognises and what the compiler does with each one.

SyntaxNameWhere it is allowedWhat the compiler does
// textSingle-line commentAnywhere outside a string, through to the end of the lineIgnores it
/* text */Block (multiline) commentAnywhere outside a string, including in the middle of a lineIgnores it
/** text */GroovyDoc commentDirectly before a class, interface, trait, method, field or propertyIgnores it, but the groovydoc tool reads it
#!/usr/bin/env groovyShebang lineOnly on the very first line of a scriptIgnores it, so Unix shells can run the script directly

A runnable script using every comment type

Save the following as comments.groovy. It uses every comment form, so you can confirm that none of them change what the script does.

#!/usr/bin/env groovy
// comments.groovy - demonstrates every Groovy comment style

/**
 * Builds a greeting for a user.
 *
 * @param name the user's name
 * @return the greeting text
 */
String greetUser(String name) {
    return "Hello, ${name}!"   // GString interpolation
}

/*
  The block below is disabled for now.
  println "This line never runs"
*/

def total = 10 /* inline block comment */ + 5
println greetUser('DevOps')
println "Total: ${total}"
println "URL: https://groovy-lang.org"   // the // inside the string is not a commentCode language: JavaScript (javascript)
$ groovy comments.groovy
Hello, DevOps!
Total: 15
URL: https://groovy-lang.org

# Or, using the shebang line on Linux/macOS:
$ chmod +x comments.groovy
$ ./comments.groovyCode language: PHP (php)

Some points to notice. The block comment in the middle of 10 /* ... */ + 5 is removed before the expression is evaluated, so total is 15. The // inside "https://groovy-lang.org" belongs to the string, because comment markers have no effect inside string literals. The shebang line only works when it is the very first line of the file, with nothing before it, not even a blank line.

Common mistakes and how to fix them

MistakeWhat happensFix
Nesting block comments: /* outer /* inner */ still outer */The first */ closes the comment, so still outer */ is parsed as code and compilation failsUse // on each line, or remove the inner /* */ before wrapping the block
Using # as a comment (shell or Python habit)Compilation error, because # only counts as a comment in a first-line shebangUse // instead
Forgetting to close /*The rest of the file is treated as comment text and the compiler reports an error at the end of the fileAdd the missing */, and let your IDE's syntax highlighting show where the comment ends
Commenting out only one half of a brace pairA { or } no longer has its partner, which gives confusing errors on later linesComment out whole blocks, or use the IDE's block-comment command on a complete selection
Writing */ inside a block comment, for example in a glob like src/**/*.groovyThe */ in the path ends the comment earlyUse // comments for text that contains */

Note: In IntelliJ IDEA, Ctrl+/ (Cmd+/ on macOS) toggles line comments and Ctrl+Shift+/ (Cmd+Option+/ on macOS) toggles a block comment. Line comments are the safer choice when you disable code, because they never nest incorrectly.

Comments in Jenkinsfiles

Both declarative and scripted Jenkins pipelines are written in Groovy, so the same comment rules apply. A common use is temporarily disabling a stage with a block comment:

pipeline {
    agent any
    stages {
        stage('Build') {
            steps {
                // Compile and package the application
                sh '''
                    # This is a shell comment inside the sh string
                    mvn -B clean package
                '''
            }
        }
        /*
        stage('Deploy') {
            steps {
                sh './deploy.sh'
            }
        }
        */
    }
}Code language: PHP (php)

Inside the sh '''...''' string, the text is a shell script, so comments there must use the shell's # syntax. A // inside that string is passed to the shell unchanged, and the shell will try to run it as a command. Outside the string, in the Groovy code, # is not valid. Because a block comment ends at the first */, check that a commented-out stage does not contain */, for example in a file pattern such as archiveArtifacts 'target/**/*.jar'.

Generating documentation from GroovyDoc comments

GroovyDoc comments use Javadoc-style tags such as @param, @return, @throws, @see, @since and @deprecated. GroovyDoc is designed for classes and their members, so put documented code in classes when you want the API pages to be useful. Script-level methods like the one in the example above end up in a generated script class.

// src/main/groovy/com/example/Greeter.groovy
package com.example

/**
 * Creates greeting messages.
 *
 * @since 1.0
 */
class Greeter {

    /** Text placed before the name. */
    String prefix = 'Hello'

    /**
     * Builds a greeting for a user.
     *
     * @param name the user's name, must not be empty
     * @return the formatted greeting
     * @throws IllegalArgumentException if name is empty
     */
    String greet(String name) {
        if (!name) throw new IllegalArgumentException('name is required')
        "${prefix}, ${name}!"
    }
}Code language: JavaScript (javascript)

You can generate HTML with the groovydoc command that ships with the Groovy distribution, or with Gradle's groovy plugin, which adds a groovydoc task.

# Command line: write HTML docs for the com.example package into ./docs
groovydoc -d docs -sourcepath src/main/groovy com.example

# Gradle (with plugins { id 'groovy' } in build.gradle)
./gradlew groovydoc
# Output: build/docs/groovydoc/index.htmlCode language: PHP (php)

Note: Groovy 3 and later also support runtime GroovyDoc. A comment that starts with /@ can be attached to the class or method and read at runtime through its groovydoc property. This is off by default and is turned on with the JVM option -Dgroovy.attach.runtime.groovydoc=true. Most projects never need it, but it explains the unusual /@ syntax if you come across it.

Practical commenting guidelines

The best practices above are a good starting point. The following points make them more concrete:

  • Explain why, not what. // retry because the artifact repo returns 503 during reindexing is useful. // increment i is not.
  • Delete dead code instead of commenting it out once it is in version control. Git keeps the history, and large commented-out blocks hide the real logic.
  • Mark unfinished work consistently with // TODO: or // FIXME: so IDEs and linters such as CodeNarc can find it.
  • Never put secrets in comments. Credentials or tokens in a commented-out line are still in the repository and its history. In Jenkins, use the credentials store.
  • Document every public class and method in shared libraries, such as Jenkins shared libraries under src/, because other teams depend on that API.

Frequently asked questions

Does Groovy support # comments?

No. The only place # is accepted is a shebang line such as #!/usr/bin/env groovy on the first line of a script. Anywhere else, use // or /* */.

Can I nest multiline comments in Groovy?

No. A block comment ends at the first */, so any text after the inner comment is parsed as code and compilation usually fails. Use // on each line when you comment out code that already contains a block comment.

How do I comment out multiple lines in a Jenkinsfile?

Wrap the lines in /* and */, or prefix each line with //. Inside sh script strings, use the shell's # comments instead, because that text is run by the shell, not by Groovy.

What is the difference between /* */ and /** */ in Groovy?

The compiler ignores both. The /** */ form is a GroovyDoc comment, which the groovydoc tool reads to build HTML API documentation when the comment sits directly before a class, method, field or property.

How do I generate GroovyDoc HTML documentation?

Run groovydoc -d docs -sourcepath src/main/groovy <package> from the command line. In a Gradle project that applies the groovy plugin, run ./gradlew groovydoc and open build/docs/groovydoc/index.html.

Related tutorials

Find Trusted Cardiac Hospitals

Compare heart hospitals by city and services โ€” all in one place.

Explore Hospitals
I'm Rajesh Kumar, a DevOps, SRE, DevSecOps, Cloud, and Platform Engineering expert passionate about sharing practical knowledge, real-world experiences, and industry best practices. I have worked at Cotocus and regularly write about technology, travel, investing, health, product reviews, and digital marketing through my various platforms. I publish technical articles at DevOps School, travel stories at Holiday Landmark, stock market insights at Stocks Mantra, health and fitness guidance at My Medic Plus, product reviews at TrueReviewNow, and SEO and digital marketing strategies at Wizbrand.

Related Posts

Cloudbees CD RO Tutorials: DSL

CloudBees CD/RO DSL is a Groovy-based language for defining projects, procedures, steps, pipelines and properties as code. You run these scripts on the server with ectool evalDsl….

Read More

Automating Jenkins Job Configuration: Job DSL, Multibranch, Job Generator, and JJB

Manually creating many Jenkins jobs is slow and error-prone. This guide compares the main automation options and shows practical jobs-as-code examples for repeatable setup.

Read More

Gradle Training Curriculum: Hands-On Learning Path for Build and DevOps Engineers

A revised, practical Gradle training guide based on the original course outline. It maps the agenda to hands-on labs, CI workflow, and team-ready build practices.

Read More

Deploying Java EE on Amazon EC2 with EC2Deploy: Workflow, Script, and Modern Lessons

This revised guide breaks down the original EC2Deploy approach for provisioning EC2 instances, deploying Java EE apps, and running JMeter tests. It also maps the same deployment pattern to modern DevOps practices.

Read More

Jenkins Pipeline Tutorials: How to create folder and subfolder?

To create folders and subfolders in Jenkins using pipeline code, you can use Jenkins Job DSL or Groovy script. Hereโ€™s how you can accomplish this in a…

Read More

Jenkins Tutorials: Meaning of $class in scripted pipeline

In Jenkins pipeline scripts, the $class parameter is used to specify the class or type of an object. The complete list of $class values depends on the…

Read More
Subscribe
Notify of
guest
0 Comments
Newest
Oldest Most Voted
0
Would love your thoughts, please comment.x
()
x