A Name in Java program by default
considered as an identifier. It may be a Class Name, Method Name,
Variable Name or Label Name.
Example:
class Test{
public static void main(String args[]){
System.out.println("HelloWorld");
int x=10;
}
}
In this program the identifiers are:-
1. Test -->Name of the class
2. main -->Name of method
3. String -->Name of a predefined
java class
4. args -->Name of Array
5. println -->Name of method
6. x -->Name of variable
Rules for defining an Identifier:
1. The only allowed characters for java
identifier in java are { a-z,A-Z,0-9,_,$ }
If we are using any other charcter we
ll get compile time error
Example:
total_number (valid)
total# (Invalid)
2. Identifiers should not start with
digit.
Example:
total123 (valid)
123total (Invalid)
3. Java Identifiers are case
Sensitive,Of Course Java language itself is treated as case-sensitive
programming language.
Example:
class Test{
int number=10; (valid)
int Number=20; (valid)
int NUMBER=30; (valid)
}
4. There is no length limit for java
identifiers. But it is not recommended to take too lengthy
identifiers.
Example:
class Test{
int
xhgxihihoiweflwedvbkbdvbdbvdfbvdfsbvfdlmbvfdlflegplrtkhgerugvterwh=10;
System.out.println(xhgxihihoiweflwedvbkbdvbdbvdfbvdfsbvfdlmbvfdlflegplrtkhgerugvterwh);
//valid and No error,but not recommended for good programmer
}
5. We can't use reserved
words(KeyWords) as identifier.
Example:
class Test{
int x=10; (valid)
int if=20; (Invalid)
}
6. All predefined java class names and
interface names, we can use as identifiers.
Example:
class Test{
public static void main(String args[]){
int String =10
System.out.println(String); //valid and
No error, but not recommended
int Runnable =20
System.out.println(Runnable); //valid
and No error, but not recommended
}
}
Note: Even though it is valid, but it
is not a good programming practice because it reduces readability and
creates confusion.
Practice Question:
which of the following are valid java
identifiers?
1. max_number
2. max#
3. 123max
4. max123
5. _$_$_$_$_
6. all@hands
7. ca$h
8. Java2Share
9. Integer
10. Int
11. int
No comments:
Post a Comment