How to count Java comments of a program that is stored in a text file?

You can read the contents of a file using the Scanner class and You can find the comments in a particular line using contains() method.


import java.util.Scanner;
public class FindingComments {
   public static void main(String[] args) throws IOException {
      Scanner sc = new Scanner(new File("HelloWorld"));
      String input;
      int single = 0;
      int multiLine = 0;
      while (sc.hasNextLine()) {
         input = sc.nextLine();
         if (input.contains("/*")) {
            multiLine ++;
         if(input.contains("//")) {
            single ++;
      System.out.println("no.of single line comments ::"+single);
      System.out.println("no.of single line comments ::"+multiLine);

Contents of the file HelloWorld −

Public class SampleProgram{
   /* This is my first java program.
      * This will print ‘Hello World’ as the output
   Public static void main(String args[]){
      //Prints Hello World
      System.out.println("Hello World");


no.of single line comments ::1
no.of single line comments ::1

Samual Sam
Samual Sam

Learning faster. Every day.

Updated on: 16-Jun-2020


Kickstart Your Career

Get certified by completing the course

Get Started