Identifer versus keyword

风格不统一 提交于 2019-11-27 22:23:23

问题


I read in the book for OCJP for Java6 the part with assertions. I reached the part where it gives me an overview of how the compiler reacts if the word 'assert' is used as keyword or as an identifier.

What is the difference between a Keyword and an identifier? Can anyone give me a simple explanation and additionally one or more examples for both?


回答1:


The terms "keyword" and "identifier" are not Java specific.

A keyword is a reserved word from the Java keyword list provide the compiler with instructions. As keywords are reserved, they cannot be used by the programmer for variable or method names.

Examples:

final
class
this
synchronized

Identifiers are the names of variables, methods, classes, packages and interfaces. They must be composed of letters, numbers, the underscore _ and the dollar sign $. Identifiers may only begin with a letter, the underscore or a dollar sign.

Examples:

int index;
String name;

index and name are valid identifiers here. int is a keyword.

A keyword cannot be used as an identifier.




回答2:


Identifiers are names of variables. For example in

int a = 3;

a would the identifier. Keywords, on the other hand, are reserved (i.e. you can't name a variable with a keyword), pre-defined words that have a specific meaning in the language. For example in

if (a == 3)
    System.out.println("Hello World");

if is a keyword. It has a specific function and cannot be used as a variable name. Moreover, the words used to declare primitive types are all keywords as well, e.g. int, char, long, boolean etc. You can see a full list of Java keywords here




回答3:


Keywords are reserved words like new,static,public,if,else,..

An identifier can be a name of any variable.

int age = 26;

"age" here is an identifier, while int is a reserved word.

The following example won't compile:

String static = "hello";
int public = 4;

you can't do this because "static" and "public" are keywords, that in this case are being used as identifiers, which is not allowed.




回答4:


I assume an identifier is your own (function name, var name, ...); and a keyword is 'class' or 'assert' or 'while' -- language defined identifiers, in other words




回答5:


The following page contains a list of Java identifiers and keywords related to 1Z0-803 OCA Certification. Java Identifiers Keywords



来源:https://stackoverflow.com/questions/12547009/identifer-versus-keyword

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!