Videos
Keywords are special words in the grammar of a language. A keyword has a special meaning in a language. Personally I like to distinguish more between reserved words and keywords and built-in types but that's just me. (I wouldn't call int a keyword for example, it's just a built-in type so at best it's a reserved word).
These things are treated differently by the compiler. The compiler knows how to handle public, int, void, class etc.
Update
Actually it's not true that you need to import the package to use the scanner:
public void M() throws FileNotFoundException {
java.util.Scanner scanner = new java.util.Scanner(new File(""));
}
This is a valid snippet of code. import just import things into your namespace. If you have for example a java.util.Scanner and a com.business.Scanner you can not import them both because you now have a conflict in your namespace: You have two Scanners.
Scanner is NOT part of the java language. int is. As far as your compiler is concerned there's no such thing as Scanner but there are such things as int, double. In essence: The definitions for these keywords are built into the compiler. Primitive data types are built-in types the compiler knows about. You do not have to tell the compiler what a double is, it just knows. However, you do have to tell your compiler what a Scanner is. (Of course, if you're writing a compiler you do have to teach the compiler you're writing what a double is).
Keywords like while, public are different because they are not data types. They are part of the grammar (and semantics) of the language. The compiler knows how to treat these. If it sees a while it produces machine code (or bytecode in java) that loops as long as a certain condition is true.
Think of a simple language with a grammar like this:
Program: <Identifier>, 'says', <Text>
Identifier: Character | Character, Identifier
Text: '"', [Character], '"'
This looks confusing but essentially this grammar means that a Program (sentence) starts with a Name, is then followed by says and then followed by Text. In this case says IS a keyword. It has a special meaning in the language. For example the compiler will produce code that displays the text on screen when it sees such a program with says in it.
The compiler follows these simple rules when it finds an identifier:
- Looks it in the list of built-in keywords (like
public,abstract,return, etc). If it is included in that list, then it is a keyword. - If not found, same with built-in types (like
int,char,double,float, etc). - If not found, looks it in current scope's definitions, in this order:
- Within the current block.
- Within the current method.
- Within the current class or interface.
- Within the current package.
- If not found, looks it in the definitions imported in the current source (through the
importdeclarations).
As you can see, the built-in types and reserved keywords have always priority, no matter the current scope or declared imports.