Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error: identifier expected when compiling java code with package statements from command line

I have a simple class with just a main method that prints something and a package statement as follows

package default;

public class Main
{
    public static void main(String[] args)
    {

        System.out.printf("something\n");
    }
}

I have put the file Main.java into a folder default and I have attempted to compile it using the following command.

javac default/Main.java

The problem is that when I try to compile the class I get the following error message verbatim

default/Main.java:1: error: <identifier> expected
package default;
       ^
1 error

I'm really confused by this. If I take the package statement out or put the code into an IDE such as eclipse, the error goes away and it works fine. I have tried scouring the internet for answers to this question and all sources say that what I'm doing should work.

I have also tried to modify the compile statement as recommended by several Stack Overflow threads by including a classpath as follows

javac -cp default default/Main.java

but the error message remains the same.

Some of my colleagues at my university have suggested that using packages outside of an IDE is impossible and that the only way for my code to compile by command line is to remove the package statement, but that answer doesn't seem right to me.

If anyone knows why I am having this issue, I would really appreciate a response. I just really want to know what I am doing wrong.

like image 311
Wesley Avatar asked May 19 '26 23:05

Wesley


1 Answers

"default", Is a keyword in java, you can't use keywords as package name or for example as a variable name. The default keyword belongs to a switch statement:

switch(x){
    case 1: 
        //do stuff if x is 1...
        break;
    default:
        //do stuff if x is not any of the other cases
        break;
}
like image 107
Lucurious Avatar answered May 22 '26 12:05

Lucurious



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!