Frosted Cupcake
Frosted Cupcake

Reputation: 1970

About phases of JAVA compiler

I have a code:

package pack;
public class St
{
    public static void main(String args[])
    {
        Int y=9;
        display(23,1);
    }
}
class Animals
{
    void display(int a,int b)
    {
        System.out.println("I am Animal Class");
    }
}

I want to know why the compiler is only showing error first in line Int y=9, why it is not showing both the errors simultaneously, i.e., if I correct Int to int, then it is showing error in display(23,1). I know that the compiler works in phases, can somebody please explain the various phases and their job, if you can please explain the phases with the help of an example, then I will be very grateful. And I want to know that if an error occurs in one phase, then the next successive phases are checked or not?

Upvotes: 2

Views: 720

Answers (2)

Vlad
Vlad

Reputation: 18633

$ javac St.java
St.java:6: error: cannot find symbol
        Int y=9;
        ^
  symbol:   class Int
  location: class St
St.java:7: error: cannot find symbol
        display(23,1);
        ^
  symbol:   method display(int,int)
  location: class St
2 errors
$ javac -Xmaxerrs 1 St.java
St.java:6: error: cannot find symbol
        Int y=9;
        ^
  symbol:   class Int
  location: class St
1 error

Both locally with JDK 1.7 and on CodingGrouding with JDK 1.8, I'm getting both errors.

If I had to guess I'd say it's a compiler-specific behavior. One could argue that you wouldn't be fixing all your errors at the same time, or that an incorrect variable declaration could cause a bunch of false positives down the line and so showing all of them might not be relevant.

Regarding phases, the Wikipedia article on compilers mentions

lexical analysis, preprocessing, parsing, semantic analysis (syntax-directed translation), code generation, and code optimization

Upvotes: 2

Armando Zavala
Armando Zavala

Reputation: 49

Having done a custom compiler during my school time, I found that some compilers work from top to bottom hence why we get the top most errors first. In my compiler class we learned that compilers work by taking everything in one character at a time. It can detect when something is something like Int y= 9; when it starts picking up the (i-n-t) part. It knows or expects the next couple characters like "y" to be the variable followed by either a number or semicolon. If you want to learn more I suggest reading or looking up specific compilers and just how exactly they work. How they parse through .java files or parse through .cpp files. Hope it helps

Upvotes: 2

Related Questions