Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java coding:: Eclipse showing Compile time error on Line 4 only why?

Tags:

java

public static void main(String[] args){
    char a=true;//Line 1
    char b=null; //Line 2
    char c='\n'; //Line 3
    char d='Hell'; //Line 4
}

Eclipse showing Compile time error on Line 4 only why? My understanding compiler reads top to bottom. so it should say compile time error on line number 1. but How is the priority goes to Line number 4. Kindly clarify. Thanks

like image 926
Raj Avatar asked Mar 29 '16 05:03

Raj


2 Answers

  1. I think here at line no. 4 there is Syntax error so compiler first check Syntax of expression so you know that this is not a right way to character like that('Hello').

  2. You saying why compiler doesn't show error on line 1 & 2 first.Its because of statement at line 1 & 2 are not wrong according to syntax.There are semantically wrong i.e. logically.

so according to me compiler first prefer syntax error of your code. I will hope you will understand it (Syntax & Semantics).

like image 178
Amit Gupta Avatar answered Sep 28 '22 18:09

Amit Gupta


To answer this question we need to understand how java compiler works in case of a Char during Lexical analysis.

Ideally compiler only expects a char to have only one character so it scans for opening ' and the end of it.

In the case above, it throws error as analyser flags an error stating that- it found more than one chars which results "Unclosed Character literal" which unfortunately happens way before compiler actually checks casting exception or Type incompatibity.

The poor IDE unaware of everything happening behind the scene gives it more priority.

You can get all the errors at your disposal by changing the ' to ":

    char a=true;//Line 1
    char b=null; //Line 2
    char c='\n'; //Line 3
    char d="Hell"; //Line 4

As now in the above condition Lex is happy and moved ahead.

like image 20
Helios Avatar answered Sep 28 '22 19:09

Helios