A Java Program, which can print it’s own source code !

I think Sajin told me about this when we were doing our BCA. While surfing the net I got a C program which was doing the same & inspired me to write this.  

———- 

package subin.rnd.algorithm.logic;

/**
 * This program tries to print the source of this program itself.
 * Of course I am not printing this comment.
 */

public class PrintMySource
{
    public static void main(String[] args)
    {
        String nl = “\n”;
        char q = ‘”‘;
        char s = (char) 92;
        String format = “package subin.rnd.algorithm.logic;%spublic class PrintMySource%s{%spublic static void main(String[] args)%s{%sString nl = %c%cn%c;%schar q = ‘%c’;%schar s = (char) 92;%sString format = %c%s%c;%sSystem.out.format(format, nl, nl, nl, nl, nl, q, s, q, nl, q, nl, nl, q, format, q, nl, nl, nl);%s}%s}”;
        System.out.format(format, nl, nl, nl, nl, nl, q, s, q, nl, q, nl, nl, q, format, q, nl, nl, nl);
    }
}

Advertisements