java which valid identifier_Is main a valid Java identifier?

How main could not be used as an identifier while it is used as identifier to declare the "main" method ?

For such a classic idiom :

public class Foo{

public static void main(String[] args){

}

}

main is not a keyword and it would probably never be a keyword in Java for obvious retro compatibility reasons.

About the question, is main a good identifier ?

First : valid for a compiler doesn't mean necessarily good.

For example the java1234 option that is proposed is also a valid identifier but that should really be avoided.

main has a very particularly and important meaning : it is used as the entry point method of classes and jars executed by the java command line.

Using main for a method name that doesn't fill the criteria to be used by the java command line would be just misleading while using it as variable name or a class name could make sense.

For example defining the class representing the entry point of an application as the Main class of the application is acceptable and so using it as variable name too such as :

public class Main {

public static void main(String args[]){

Main main = new Main();

// ...

}

}

In a general way, in Java, multiple characters or "words" are considered valid identifiers for the compiler but are strongly discouraged to be used in the client code (but generated code may do that : nested classes for example) as not readable and/or really misleading.

For example this could be valid for the compiler :

public class Object { // 1

public void foo() {

...

}

}

public class BadChosenIdentifier {

public static void main() { // 2

new BadChosenIdentifier().toString(new Object());

}

public void toString(Object java1234) { // 3, 4

String _result$ = java1234 + " -> to avoid"; // 4

System.out.println(_result$);

}

}

But we don't want :

to name Object our class as this is defined in java.lang(1).

to name a method main() if doesn't fill the criteria to be used by the java command line (2).

to overload the Object.toString() method (3).

to name our variables with _, $ or any surprising/unmeaningful characters that go against the shared naming conventions (4).

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值