Search code examples
javaccompiler-construction

How is language specification created


I wanted to ask, what is java written in, but I found an answer to this on stackexchange, which said, you don't write language with a language, it's a specification, but the JDK is written in C.

Now, my question is, if the JDK is written in C, is Java basically a different form of the C language, like an extension or something, with more features added? How is this specification created, and what's the relationship between these three things:

  • The tool that interprets the specification(like the JDK)
  • The specification itself
  • The language the tool was created in.

Solution

  • I think you are misunderstanding a few things, so let's go to the basics first:

    A computer program is nothing more than a set of instructions that are read by the processor and then executed. A list of tasks that are executed one by one.

    Java uses something that is called the Java Runtime Environment (JRE). The JRE is sort of (not exactly) a virtual processor, with its own instruction set called java byte code. This 'virtual processor' runs inside of your operating system.

    The Java Runtime Environment is written in some language. The Sun JRE is written in C. The C code is in turn compiled into the machine code of your real processor (So code your processor understands).

    Java is compiled into java byte code.

    So to answer your question: A specification is nothing more than a description of how the java programming language should behave and what it looks like. Basically a regular text document you can write in something like word.

    With this specification programmers can build a compiler. A compiler is a program that changes java code like this:

    for (int i = 2; i < 1000; i++) {
        for (int j = 2; j < i; j++) {
            if (i % j == 0)
                continue outer;
        }
        System.out.println (i);
    }
    

    into bytecode that looks like this

    0:   iconst_2
    1:   istore_1
    2:   iload_1
    3:   sipush  1000
    6:   if_icmpge       44
    9:   iconst_2
    10:  istore_2
    11:  iload_2
    12:  iload_1
    13:  if_icmpge       31
    16:  iload_1
    17:  iload_2
    18:  irem
    19:  ifne    25
    22:  goto    38
    25:  iinc    2, 1
    28:  goto    11
    31:  getstatic       #84; // Field java/lang/System.out:Ljava/io/PrintStream;
    34:  iload_1
    35:  invokevirtual   #85; // Method java/io/PrintStream.println:(I)V
    38:  iinc    1, 1
    41:  goto    2
    44:  return
    

    The compiler program that does this can be written in any language, however it is recommended to write it into low level languages like C++ to make the compiling process quicker.