From Wikipedia, the free encyclopedia
A snippet of Java code with keywords highlighted in blue and bold font
In the Java programming language, a keyword is any one of 67 reserved words[1] that have a predefined meaning in the language. Because of this, programmers cannot use keywords in some contexts, such as names for variables, methods, classes, or as any other identifier.[2] Of these 67 keywords, 16 of them are only contextually reserved, and can sometimes be used as an identifier, unlike standard reserved words. Due to their special functions in the language, most integrated development environments for Java use syntax highlighting to display keywords in a different colour for easy identification.
List of Java keywords[edit]
_
- Added in Java 9, the underscore has become a keyword and cannot be used as a variable name anymore.[3]
abstract
- A method with no definition must be declared as abstract and the class containing it must be declared as abstract. Abstract classes cannot be instantiated. Abstract methods must be implemented in the sub classes. The abstract keyword cannot be used with variables or constructors. Note that an abstract class isn’t required to have an abstract method at all.
assert
(added in J2SE 1.4)[4]- Assert describes a predicate (a true–false statement) placed in a Java program to indicate that the developer thinks that the predicate is always true at that place. If an assertion evaluates to false at run-time, an assertion failure results, which typically causes execution to abort. Assertions are disabled at runtime by default, but can be enabled through a command-line option or programmatically through a method on the class loader.
boolean
- Defines a boolean variable for the values «true» or «false» only. By default, the value of boolean primitive type is false. This keyword is also used to declare that a method returns a value of the primitive type
boolean
.
break
- Used to end the execution in the current loop body.
- Used to break out of a
switch
block.
byte
- The
byte
keyword is used to declare a field that can hold an 8-bit signed two’s complement integer.[5][6] This keyword is also used to declare that a method returns a value of the primitive typebyte
.[7][8]
case
- A statement in the
switch
block can be labeled with one or morecase
ordefault
labels. Theswitch
statement evaluates its expression, then executes all statements that follow the matchingcase
label; seeswitch
.[9][10]
catch
- Used in conjunction with a
try
block and an optionalfinally
block. The statements in thecatch
block specify what to do if a specific type of exception is thrown by thetry
block.
char
- Defines a character variable capable of holding any character of the java source file’s character set.
class
- A type that defines the implementation of a particular kind of object. A class definition defines instance and class fields, methods, and inner classes as well as specifying the interfaces the class implements and the immediate superclass of the class. If the superclass is not explicitly specified, the superclass is implicitly
Object
. The class keyword can also be used in the form Class.class to get a Class object without needing an instance of that class. For example, String.class can be used instead of doing new String().getClass().
const
- Unused but reserved.
continue
- Used to resume program execution at the end of the current loop body. If followed by a label,
continue
resumes execution at the end of the enclosing labeled loop body.
default
- The
default
keyword can optionally be used in a switch statement to label a block of statements to be executed if nocase
matches the specified value; seeswitch
.[9][10] Alternatively, thedefault
keyword can also be used to declare default values in a Java annotation. From Java 8 onwards, thedefault
keyword can be used to allow an interface to provide an implementation of a method.
do
- The
do
keyword is used in conjunction withwhile
to create a do-while loop, which executes a block of statements associated with the loop and then tests a boolean expression associated with thewhile
. If the expression evaluates totrue
, the block is executed again; this continues until the expression evaluates tofalse
.[11][12]
double
- The
double
keyword is used to declare a variable that can hold a 64-bit double precision IEEE 754 floating-point number.[5][6] This keyword is also used to declare that a method returns a value of the primitive typedouble
.[7][8]
else
- The
else
keyword is used in conjunction withif
to create an if-else statement, which tests a boolean expression; if the expression evaluates totrue
, the block of statements associated with theif
are evaluated; if it evaluates tofalse
, the block of statements associated with theelse
are evaluated.[13][14]
enum
(added in J2SE 5.0)[4]- A Java keyword used to declare an enumerated type. Enumerations extend the base class
Enum
.
extends
- Used in a class declaration to specify the superclass; used in an interface declaration to specify one or more superinterfaces. Class X extends class Y to add functionality, either by adding fields or methods to class Y, or by overriding methods of class Y. An interface Z extends one or more interfaces by adding methods. Class X is said to be a subclass of class Y; Interface Z is said to be a subinterface of the interfaces it extends.
- Also used to specify an upper bound on a type parameter in Generics.
final
- Define an entity once that cannot be changed nor derived from later. More specifically: a final class cannot be subclassed, a final method cannot be overridden, and a final variable can occur at most once as a left-hand expression on an executed command. All methods in a final class are implicitly
final
.
finally
- Used to define a block of statements for a block defined previously by the
try
keyword. Thefinally
block is executed after execution exits thetry
block and any associatedcatch
clauses regardless of whether an exception was thrown or caught, or execution left method in the middle of thetry
orcatch
blocks using thereturn
keyword.
float
- The
float
keyword is used to declare a variable that can hold a 32-bit single precision IEEE 754 floating-point number.[5][6] This keyword is also used to declare that a method returns a value of the primitive typefloat
.[7][8]
for
- The
for
keyword is used to create a for loop, which specifies a variable initialization, a boolean expression, and an incrementation. The variable initialization is performed first, and then the boolean expression is evaluated. If the expression evaluates totrue
, the block of statements associated with the loop are executed, and then the incrementation is performed. The boolean expression is then evaluated again; this continues until the expression evaluates tofalse
.[15]
- As of J2SE 5.0, the
for
keyword can also be used to create a so-called «enhanced for loop»,[16] which specifies an array orIterable
object; each iteration of the loop executes the associated block of statements using a different element in the array orIterable
.[15]
goto
- Unused but reserved.
if
- The
if
keyword is used to create an if statement, which tests a boolean expression; if the expression evaluates totrue
, the block of statements associated with the if statement is executed. This keyword can also be used to create an if-else statement; seeelse
.[13][14]
implements
- Included in a class declaration to specify one or more interfaces that are implemented by the current class. A class inherits the types and abstract methods declared by the interfaces.
import
- Used at the beginning of a source file to specify classes or entire Java packages to be referred to later without including their package names in the reference. Since J2SE 5.0,
import
statements can importstatic
members of a class.
instanceof
- A binary operator that takes an object reference as its first operand and a class or interface as its second operand and produces a boolean result. The
instanceof
operator evaluates to true if and only if the runtime type of the object is assignment compatible with the class or interface.
int
- The
int
keyword is used to declare a variable that can hold a 32-bit signed two’s complement integer.[5][6] This keyword is also used to declare that a method returns a value of the primitive typeint
.[7][8]
interface
- Used to declare a special type of class that only contains abstract or default methods, constant (
static final
) fields andstatic
interfaces. It can later be implemented by classes that declare the interface with theimplements
keyword. As multiple inheritance is not allowed in Java, interfaces are used to circumvent it. An interface can be defined within another interface.
long
- The
long
keyword is used to declare a variable that can hold a 64-bit signed two’s complement integer.[5][6] This keyword is also used to declare that a method returns a value of the primitive typelong
.[7][8]
native
- Used in method declarations to specify that the method is not implemented in the same Java source file, but rather in another language.[8]
new
- Used to create an instance of a class or array object. Using keyword for this end is not completely necessary (as exemplified by Scala), though it serves two purposes: it enables the existence of different namespace for methods and class names, it defines statically and locally that a fresh object is indeed created, and of what runtime type it is (arguably introducing dependency into the code).
package
- Java package is a group of similar classes and interfaces. Packages are declared with the
package
keyword.
private
- The
private
keyword is used in the declaration of a method, field, or inner class; private members can only be accessed by other members of their own class.[17]
protected
- The
protected
keyword is used in the declaration of a method, field, or inner class; protected members can only be accessed by members of their own class, that class’s subclasses or classes from the same package.[17]
public
- The
public
keyword is used in the declaration of a class, method, or field; public classes, methods, and fields can be accessed by the members of any class.[17]
return
- Used to finish the execution of a method. It can be followed by a value required by the method definition that is returned to the caller
short
- The
short
keyword is used to declare a field that can hold a 16-bit signed two’s complement integer.[5][6] This keyword is also used to declare that a method returns a value of the primitive typeshort
.[7][8]
static
- Used to declare a field, method, or inner class as a class field. Classes maintain one copy of class fields regardless of how many instances exist of that class.
static
also is used to define a method as a class method. Class methods are bound to the class instead of to a specific instance, and can only operate on class fields. Classes and interfaces declared asstatic
members of another class or interface are actually top-level classes and are not inner classes.
super
- Inheritance basically used to achieve dynamic binding or run-time polymorphism in java. Used to access members of a class inherited by the class in which it appears. Allows a subclass to access overridden methods and hidden members of its superclass. The
super
keyword is also used to forward a call from a constructor to a constructor in the superclass. - Also used to specify a lower bound on a type parameter in Generics.
switch
- The
switch
keyword is used in conjunction withcase
anddefault
to create a switch statement, which evaluates a variable, matches its value to a specificcase
, and executes the block of statements associated with thatcase
. If nocase
matches the value, the optional block labelled bydefault
is executed, if included.[9][10]
synchronized
- Used in the declaration of a method or code block to acquire the mutex lock for an object while the current thread executes the code.[8] For static methods, the object locked is the class’s
Class
. Guarantees that at most one thread at a time operating on the same object executes that code. The mutex lock is automatically released when execution exits the synchronized code. Fields, classes and interfaces cannot be declared as synchronized.
this
- Used to represent an instance of the class in which it appears.
this
can be used to access class members and as a reference to the current instance. Thethis
keyword is also used to forward a call from one constructor in a class to another constructor in the same class.
throw
- Causes the declared exception instance to be thrown. This causes execution to continue with the first enclosing exception handler declared by the
catch
keyword to handle an assignment compatible exception type. If no such exception handler is found in the current method, then the method returns and the process is repeated in the calling method. If no exception handler is found in any method call on the stack, then the exception is passed to the thread’s uncaught exception handler.
throws
- Used in method declarations to specify which exceptions are not handled within the method but rather passed to the next higher level of the program. All uncaught exceptions in a method that are not instances of
RuntimeException
must be declared using thethrows
keyword.
transient
- Declares that an instance field is not part of the default serialized form of an object. When an object is serialized, only the values of its non-transient instance fields are included in the default serial representation. When an object is deserialized, transient fields are initialized only to their default value. If the default form is not used, e.g. when a serialPersistentFields table is declared in the class hierarchy, all
transient
keywords are ignored.[18][19]
try
- Defines a block of statements that have exception handling. If an exception is thrown inside the
try
block, an optionalcatch
block can handle declared exception types. Also, an optionalfinally
block can be declared that will be executed when execution exits thetry
block andcatch
clauses, regardless of whether an exception is thrown or not. Atry
block must have at least onecatch
clause or afinally
block.
void
- The
void
keyword is used to declare that a method does not return any value.[7]
volatile
- Used in field declarations to guarantee visibility of changes to variables across threads. Every read of a volatile variable will be read from main memory, and not from the CPU cache, and that every write to a volatile variable will be written to main memory, and not just to the CPU cache.[20] Methods, classes and interfaces thus cannot be declared volatile, nor can local variables or parameters.
while
- The
while
keyword is used to create a while loop, which tests a boolean expression and executes the block of statements associated with the loop if the expression evaluates totrue
; this continues until the expression evaluates tofalse
. This keyword can also be used to create a do-while loop; seedo
.[11][12]
Reserved Identifiers[edit]
The following identifiers are contextual keywords, and are only restricted in some contexts:
exports
module
non-sealed
- Used to declare that a class or interface which extends a sealed class can be extended by unknown classes.[21]
open
opens
permits
- The permits clause specifies the classes that are permitted to extend a sealed class.[21]
provides
record
requires
sealed
- A sealed class or interface can only be extended or implemented by classes and interfaces permitted to do so.[21]
to
transitive
uses
var
- A special identifier that cannot be used as a type name (since Java 10).[22]
with
yield
- Used to set a value for a switch expression, when using labelled statement groups (for example,
case L:
).[23]
Reserved words for literal values[edit]
true
- A boolean literal value.
false
- A boolean literal value.
null
- A reference literal value.
Unused[edit]
const
- Although reserved as a keyword in Java,
const
is not used and has no function.[2][24] For defining constants in Java, see thefinal
keyword.
goto
- Although reserved as a keyword in Java,
goto
is not used and has no function.[2][24]
strictfp
(added in J2SE 1.2)[4]- Although reserved as a keyword in Java,
strictfp
is obsolete, and no longer has any function.[25] Previously this keyword was used to restrict the precision and rounding of floating point calculations to ensure portability.[8]
See also[edit]
- Java annotation
References[edit]
- ^ «Java Platform, Standard Edition Java API Reference».
{{cite web}}
: CS1 maint: url-status (link) - ^ a b c «Java Language Specification — Section 3.9: Keywords». The Java Language Specification. Oracle. 2018-08-21. Retrieved 2018-12-25.
- ^ Goetz, Brian. «Warning about single underscore identifier». OpenJDK Lambda Development.
- ^ a b c «Java Language Keywords». The Java Tutorials. Sun Microsystems, Inc. Retrieved 2017-07-24.
- ^ a b c d e f «Primitive Data Types». The Java Tutorials. Sun Microsystems, Inc. February 14, 2008. Retrieved 2008-12-03.
- ^ a b c d e f Flanagan 2005, p. 22.
- ^ a b c d e f g «Returning a Value from a Method». The Java Tutorials. Sun Microsystems, Inc. February 14, 2008. Retrieved 2008-12-03.
- ^ a b c d e f g h i Flanagan 2005, pp. 66–67.
- ^ a b c «The switch Statement». The Java Tutorials. Sun Microsystems, Inc. February 14, 2008. Retrieved 2014-12-18.
- ^ a b c Flanagan 2005, pp. 46–48.
- ^ a b «The while and do-while Statements». The Java Tutorials. Sun Microsystems, Inc. February 14, 2008. Retrieved 2008-12-03.
- ^ a b Flanagan 2005, pp. 48–49.
- ^ a b «The if-then and if-then-else Statements». The Java Tutorials. Sun Microsystems, Inc. February 14, 2008. Retrieved 2008-12-03.
- ^ a b Flanagan 2005, pp. 44–46.
- ^ a b «The for Statement». The Java Tutorials. Sun Microsystems, Inc. February 14, 2008. Retrieved 2008-12-03.
- ^ Flanagan 2005, pp. 50–54.
- ^ a b c «Controlling Access to Members of a Class». The Java Tutorials. Sun Microsystems, Inc. February 14, 2008. Retrieved 2008-12-03.
- ^ «Java Object Serialization Specification version 1.5.0». Sun/Oracle. 2004. 1.5 Defining Serializable Fields for a Class. Retrieved 2010-09-16.[permanent dead link]
- ^
Grosso, William (November 21, 2001). «Java RMI: Serialization». ONJava. O’Reilly Media. Declaring serialPersistentFields. Retrieved 2010-09-16. - ^ «Java Volatile Keyword».
- ^ a b c «Sealed Classes». docs.oracle.com. Oracle Corporation. Retrieved 2021-08-07.
- ^ «Chapter 3. Lexical Structure». docs.oracle.com. Retrieved 2018-12-25.
- ^ «Switch Expressions». docs.oracle.com. Oracle Corporation. Retrieved 2020-12-27.
- ^ a b Flanagan 2005, p. 20.
- ^ «JEP 306: Restore Always-Strict Floating-Point Semantics».
{{cite web}}
: CS1 maint: url-status (link)
External links[edit]
- Gosling, James; Joy, Bill; Steele, Guy; Bracha, Gilad (June 2005). Java Language Specification (Third ed.). Addison-Wesley Professional. ISBN 978-0-321-24678-3. Retrieved 2008-12-03.
- Flanagan, David (March 2005). Java in a Nutshell (Fifth ed.). O’Reilly Media. ISBN 978-0-596-00773-7. Retrieved 2010-03-03.
Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article
Keywords or Reserved words are the words in a language that are used for some internal process or represent some predefined actions. These words are therefore not allowed to use as variable names or objects. If we do we will get a compile-time error as shown below as follows:
Illustration:
Java
class
HelloWorld {
public
static
void
main(String[] args)
{
int
this
=
"Hello World!"
;
System.out.println(
this
);
}
}
Output:
Errors in Code : Compiler Error prog.java:11: error: not a statement int this = "Hello World!"; // Note "this" is a reserved word in java ^ prog.java:11: error: ';' expected int this = "Hello World!"; // Note "this" is a reserved word in java ^ 2 errors
Java contains a list of keywords or reserved words which are also highlighted with different colors be it an IDE or editor in order to segregate the differences between flexible words and reserved words. They are listed below in the table with the primary action associated with them.
S.No | Keyword | Usage |
---|---|---|
1. | abstract | Specifies that a class or method will be implemented later, in a subclass |
2. | assert | Assert describes a predicate placed in a java program to indicate that the developer thinks that the predicate is always true at that place. |
3. | boolean | A data type that can hold True and False values only |
4. | break | A control statement for breaking out of loops. |
5. | byte | A data type that can hold 8-bit data values |
6. | case | Used in switch statements to mark blocks of text |
7. | catch | Catches exceptions generated by try statements |
8. | char | A data type that can hold unsigned 16-bit Unicode characters |
9. | class | Declares a new class |
10. | continue | Sends control back outside a loop |
11. | default | Specifies the default block of code in a switch statement |
12. | do | Starts a do-while loop |
13. | double | A data type that can hold 64-bit floating-point numbers |
14. | else | Indicates alternative branches in an if statement |
15. | enum | A Java keyword is used to declare an enumerated type. Enumerations extend the base class. |
16. | extends | Indicates that a class is derived from another class or interface |
17. | final | Indicates that a variable holds a constant value or that a method will not be overridden |
18. | finally | Indicates a block of code in a try-catch structure that will always be executed |
19. | float | A data type that holds a 32-bit floating-point number |
20. | for | Used to start a for loop |
21. | if | Tests a true/false expression and branches accordingly |
22. | implements | Specifies that a class implements an interface |
23. | import | References other classes |
24. | instanceof | Indicates whether an object is an instance of a specific class or implements an interface |
25. | int | A data type that can hold a 32-bit signed integer |
26. | interface | Declares an interface |
27. | long | A data type that holds a 64-bit integer |
28. | native | Specifies that a method is implemented with native (platform-specific) code |
29. | new | Creates new objects |
30. | null | This indicates that a reference does not refer to anything |
31. | package | Declares a Java package |
32. | private | An access specifier indicating that a method or variable may be accessed only in the class it’s declared in |
33. | protected | An access specifier indicating that a method or variable may only be accessed in the class it’s declared in (or a subclass of the class it’s declared in or other classes in the same package) |
34. | public | An access specifier used for classes, interfaces, methods, and variables indicating that an item is accessible throughout the application (or where the class that defines it is accessible) |
35. | return | Sends control and possibly a return value back from a called method |
36. | short | A data type that can hold a 16-bit integer |
37 | static | Indicates that a variable or method is a class method (rather than being limited to one particular object) |
38. | strictfp | A Java keyword is used to restrict the precision and rounding of floating-point calculations to ensure portability. |
39. | super | Refers to a class’s base class (used in a method or class constructor) |
40. | switch | A statement that executes code based on a test value |
41. | synchronized | Specifies critical sections or methods in multithreaded code |
42. | this | Refers to the current object in a method or constructor |
43. | throw | Creates an exception |
44. | throws | Indicates what exceptions may be thrown by a method |
45. | transient | Specifies that a variable is not part of an object’s persistent state |
46. | try | Starts a block of code that will be tested for exceptions |
47. | void | Specifies that a method does not have a return value |
48. | volatile | This indicates that a variable may change asynchronously |
49. | while | Starts a while loop |
Note:
- The keywords const and goto are reserved, even they are not currently in use.
- Currently they are no longer supported in Java.
const Reserved for future use goto Reserved for future use
- true, false and null look like keywords, but in actual they are literals. However they still can’t be used as identifiers in a program.
- These keywords cannot be used as a variable. Check out this article for more on the rules of variable declarations.
Like Article
Save Article
Reserved Words in Java
Here’s the full list of words you cannot use in Java
Updated on January 27, 2019
Reserved words are words that cannot be used as object or variable names in a Java program because they’re already used by the syntax of the Java programming language.
If you ttempt to use any of the words below as identifiers in your Java programs, you’ll get an error like the one below.
List of Reserved Java Keywords
abstract | assert | boolean | break | byte | case |
catch | char | class | const | continue | default |
double | do | else | enum | extends | false |
final | finally | float | for | goto | if |
implements | import | instanceof | int | interface | long |
native | new | null | package | private | protected |
public | return | short | static | strictfp | super |
switch | synchronized | this | throw | throws | transient |
true | try | void | volatile | while |
*The strictfp keyword was added to this list in Java Standard Edition version 1.2, assert in version 1.4, and enum in version 5.0.
Even though goto and const are no longer used in the Java programming language, they still cannot be used as keywords.
What Happens If You Use a Reserved Word?
Let’s say you try to create a new class and name it using a reserved word, like this:
// you can't use finally as it's a reserved word!
class finally {public static void main(String[] args) {
//class code..
}
}
Instead of compiling, the Java program will instead give the following error:
expected
Back to: Java Tutorials For Beginners and Professionals
Identifiers and Reserved Words in Java with Examples
In this article, I am going to discuss the Identifiers and Reserved Words in Java with Examples. Please read our previous article, where we discussed Variables in Java with examples. At the end of this article, you will understand what are Identifiers and its need as well as you will also understand Java Reserved Words which are also called as java Keywords.
Identifiers in Java:
All Java components require names. Name used for classes, methods, interfaces, and variables are called identifiers. It allows a programmer to refer to the item from other places in the program. There are some reserved words in Java, which we can’t use as identifiers. In addition, you have to follow some rules before declaring an identifier. So, let’s discuss everything in detail.
For example int age; Here, age is a variable (an identifier). You cannot use the keyword as a variable name because keywords have predefined meanings. For example int double; This code is wrong because double is a keyword and you cannot use it as a variable.
List of some valid identifiers in Java
- MyVariable
- myvariable
- x
- I
- my_Variable
- _myvariable
- $myvariable
- sum_of_array
- MYVARIABLE
- dataflair123
List of some invalid identifiers in Java
- My Variable (it contains a space)
- 123gkk (it begins with numbers)
- a+c (plus sign is not an alphanumeric character)
- variable-2 (the hyphen is not allowed)
- sum_&_difference (ampersand is not an alphanumeric character)
- O’Reilly (the apostrophe is not an alphanumeric character)
Rules for defining an Identifier in Java:
- The only allowed characters in java identifiers are a to z, A to Z, 0 to 9, $ and _(Underscore). If we are using any other character then we will get a compilation error.
- Identifiers can’t start with digit i.e., 123name is not valid.
- Java identifiers are case sensitive of course java language itself considered as case sensitive programming language. i.e., name, Name, NAME both are different variable names.
- There is no length limit for java identifiers but it is not recommended to take too length identifiers.
- We can’t use reserved words as identifiers otherwise we will get a compilation error. i.e., int if = 20; here we will get compilation error.
- All predefined java class names and interface names we can use as identifiers. i.e., int String = 20; here we won’t get any compilation error. But it is not a good programming practice.
Example:
public class Test { public static void main(String[] args) { int a = 100; System.out.println("Hai this is Ashok"); } }
In the above example, we have 5 Identifiers: Test, main, String, args, a.
Reserved Words in Java:
The Reserved Words in Java are pre-defined for some special purpose and you cannot create a variable, class name, or method name with these names. It is used to represent functionality in programs. They can be briefly categorized into two parts: keywords(50) and literals(3).
Keywords: It defines functionality.
Literals: It is used to define values.
List of Java Keywords:
abstract | assert | boolean | break | byte |
case | catch | char | class | const |
continue | default | do | double | else |
enum | extends | final | finally | float |
for | goto | if | implements | import |
instanceOf | int | interface | long | native |
new | package | private | protected | public |
return | short | static | strictfp | super |
switch | synchronized | this | throw | throws |
transient | try | void | volatile | while |
Instead of these keywords, you cannot use true, false, and null as identifiers because these are Literals. To know more about literals, Please read our Java Literals article.
Note: The keywords const and goto are reserved, even though they are not currently used. In place of const, the final keyword is used. Some keywords like strictfp are included in later versions of Java.
In the next article, I am going to discuss Control Flow Statements in Java with Examples. Here, in this article, I try to explain Identifiers and Reserved Words in Java with Examples and I hope you like this Identifier and Reserved Words in Java with Examples article. I would like to have your feedback. Please post your feedback, question, or comments about this article.
A predefined identifier that has special meaning in a Java program outside comment and string is called a Keyword. Or, A keyword is a reserved word in Java language inside the compiler and JVM that perform a unique and special operation. A word that is created as part of the compiler and JVM software to represent a value is called Reserved words. We will see the complete list of Java keywords in detail.
In Java, there are 64 reserved words, among them 51 are keywords, 3 are literals and 10 restricted words are there.
Reserved words (64)
- Keywords (51)
- Literals (3)
- Restricted words (10)
Keywords are used to communicate with compiler and JVM to perform one special operation on our program.
We can categories Java keywords list based on their uses.
1) Java Keywords list used for data types or return types (9)
Integer values
byte
short
int
long
Floating point values
float
double
Non-numeric values
char
boolean
void
Among these 9 Java keywords list, the first 8 are used for both data type and return values. But “void” is used only for the return type. If the method doesn’t return any value then the return type of the method is void.
2) List of Java keywords used in control statements (11)
Used in conditional statements
if
else
switch
case
default
Keywords used in loop
do
while
for
Keywords used in control transfer
break
continue
return
3) Keywords used for modifiers (11)
Modifiers
static
final
abstract
native
transient
volatile
synchronized
strictfp
Access Modifiers
private
protected
public
The “default” is not a keyword. When we don’t use any accessibility modifiier while declaring class/methods then by default its accessibility within the package.
4) Keywords used while defining a Java class (7)
Class related keywords
class
interface
enum
Inheritance relationship related keywords
extends
implements
Package related keywords
import
package
5) Object related keywords list (4)
Object representation
this
super
instanceof
new
6) Java keywords list used in Exception Handling (6)
try
catch
finally
throw
throws
assert
7) Unused keywords (2)
goto
const
Important points
There are some important points related to Java keywords,
- In Java, every keyword is a reserved word but every reserved word is not a keyword.
- We can’t use a keyword for a user-defined identifier name. It can’t be used for variables, methods, class names.
- Except for underscore (
_
), all remaining keywords are the combination of lowercase letters and doesn’t contain any digit and special characters.
Among these keywords, most of them are given in the Java1.0 version onwards but some of them were introduced later. Those keywords list with java version is given below.
Keyword | Java Version |
strictfp | 1.2 |
assert | 1.4 |
enum | 1.5 |
_ | 9 |
Unused Keywords in Java
Among 51 keywords, 49 keywords are used keywords and 2 are unused keywords. The unused kwywords are:- goto and const.
In Java, goto doesn’t have any special meaning, so it might be used as an identifier. If we use the goto keyword as an identifier, then the programmers coming from C, C++, and Python will get confusion. It had already created a lot of problems in many languages. Therefore, it is not allowed to use the goto keyword in Java.
In C/C++ the const keyword is used to define the variables as constant. In Java final keyword is already there to define constant, which is applicable on variables/methods. So, the const keyword is also not allowed in Java.
From the Java9 version onwards we can’t use a single underscore(_
) as an identifier either for naming a class/variable/method or any other programming element. But identifiers like hello_world are valid because it is using underscore. Underscore(_
) is added as a keyword for not getting conflicts with other languages like Python. We can use Java9 JVM either for running Python or Java-based programs. To run Python programs in JVM software a new rule is created that is:- underscore(_) is not allowed as an identifier as per Python rule. So, the same rule is implemented in Java compiler software.
Java doesn’t require “goto”, “const” and ‘_’ keywords hence they aren’t implemented. Even though they aren’t required, Java designers created them as keywords for stopping Java programmers to use them as user-defined identifiers in their programs. If we use them in our Java program then we will get a compile-time error.
Table with all Java keywords
_ |
extends |
protected |
abstract |
final |
public |
assert |
finally |
return |
boolean |
float |
short |
break |
for |
static |
byte |
goto |
strictfp |
case |
if |
super |
catch |
implements |
switch |
char |
import |
synchronized |
class |
instanceof |
this |
const |
int |
throw |
continue |
interface |
throws |
default |
long |
transient |
do |
native |
try |
double |
new |
void |
else |
package |
volatile |
enum |
private |
while |
Reserved literals in Java
Boolean literals:- true
, and false
Null literals:- null
These three are reserved words and literals(value), not keywords. Even though these words are not keywords we can’t use them as user-defined identifiers. Boolean literals are used for boolean data types. The null is the default value for an object reference.
Restricted Words in Java
To support the Java9 module system and to create and use the module in Java we got 10 restricted keywords. Restricted keywords mean these keywords are meant for use only in module programming. These keywords don’t have any meaning in regular programming inside a class/interface program. So, inside class/interface we can use them as a user-defined identifier. This facility added to support backward compatibility. It means for not getting errors on the project those are developed using Java8 or earlier version.
- module
- requires
- transitive
- exports
- open
- opens
- to
- provides
- with
- uses
All the above 10 keywords can’t be used individually. Some keywords must use in combination with other keywords. We must use the transitive
keyword in combination with requires
keyword. We must use the keyword to
in combination with either export
or with opens
. Similarly, with
must be used with provides
.
See:- Quiz on Java keywords
If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or do you find anything incorrect? Let us know in the comments. Thank you!
abstract
assert
boolean
break
byte
case
catch
char
class
const
continue
default
do
double
else
enum
extends
final
finally
float
for
goto
if
implements
import
int
interface
long
native
new
null
package
private
protected
public
return
short
static
strictfp
super
switch
synchronized
this
throw
throws
transient
try
void
volatile
while