Java Keywords Tutorial
1. Introduction
In this article, we will look at words Java considers as Keywords. We will explore why they are used and what they are along with some usage examples.
2. What is a Keyword in Java and why do we need them?
The Java Compiler uses some reserved words called Keywords to compile and run Java Programs. Each reserved word has a special meaning attached to it and is used while generating the java bytecode. For example: when we declare a variable as “int”, the java bytecode understands that a store/load operation needs to be done.
Using these keywords Java understands how to store, load, and use variables or identifiers in the programs. Keywords cannot be used as identifiers i.e. Class names, variables names, or method names in Java.
Using a Java Keyword as an identifier name will result in a compiler error. Consider the following program.
KeywordExample.java
public class KeywordExample{ public static void main(String[] args) { int boolean = 123; } }
If compiled using the command line, it results in a compile-time error as follows:
If we use an IDE like example Eclipse or IntelliJ etc, it will prompt an error during compile time itself. For if we type out the same example in an IDE, we get the following error. Also, note that most IDEs will color the keyword in some color like maroon.
3. How many keywords in Java?
There are a total of 51 keywords in Java as of now. Java has added some keywords in the later versions as well. For example, the most recently added keyword is exported.
Below are all the keywords, grouped by their categories. The categories are broadly 8 different categories:
3.1 Data types
These are primitive data types that are used in Java. They are:
- boolean
- byte
- char
- double
- float
- int
- long
- short
3.2 Access modifiers
Access modifiers are used with Classes, methods, and variables. They decide the scope/visibility of the variable being used with them. E.g.: If a variable is marked as “public”, it is accessible from anywhere. The access modifiers are as follows:
- public
- private
- protected
3.3 Class, method, and variable modifiers
These are non-access modifiers. These can be used with classes, methods, and variables. These keywords define the behavior.
- abstract
- class
- default
- extends
- final
- implements
- interface
- native
- new
- static
- strictfp
- synchronized
- transient
- var
- record
- volatile
3.4 Package control
These are keywords used to create and import packages in Java. From Java 9 onwards a new keyword export has also been added to this list.
- import
- package
- exports
3.5 Flow control
Flow control keywords are used to control the flow of execution of a Java program. These keywords are related to loops and conditional keywords
- if
- else
- for
- while
- do
- switch
- case
- break
- continue
- instanceOf
- return
- default
- yield
3.6 Enumeration
Enum is a special class that represents a group of constants. The keyword related to the Enumeration is
- enum
3.7 Error handling
Error handling keywords are used for exception handling and for testing. The keywords are as follows:
- assert
- catch
- try
- finally
- throw
- throws
3.8 Others/Miscellaneous
These are some other keywords used in Java.
- super
- this
- void
Java does not use these keywords but has reserved them as keywords.
- const
- goto
4. Java Keyword Examples
We will look at examples for Primitive data types and access modifiers. Then we will look at a sample application for understanding how to use the rest of the modifiers.
4.1 Primitive Data Types
Java is a strongly-typed language. This means that the user needs to declare a data type for every variable else Java cannot compile it. Primitive data types are the types which have a size range associated with them. They do not have any other methods that we can access. There are in total 8 primitive types in Java. The types with their size ranges are as follows
Data type | Storage size | Range of values |
---|---|---|
byte | 8-bit | -128 to 127 |
short | 16-bit | -32768 to 32767 |
int | 32-bit | 0 to 232 -1 (Java 8 and later) |
long | 64-bit | 0 to 264 -1 (Java 8 and later) |
float | single-precision 32-bit IEEE 754 floating point | 3.40282347 x 1038 to 1.40239846 x 10-45 |
double | double-precision 64-bit IEEE 754 floating point | 1.7976931348623157 x 10308 to 4.9406564584124654 x 10-324 |
boolean | 1 bit | true or false |
char | 16-bit Unicode character | ‘\u0000’ to ‘\uffff’ |
More information related to Java datatypes is available here.
4.1.1 Declaration of primitive types.
The first three examples show the declaration of primitive data types.
KeywordsApp.java
public class KeywordsApp{ public static void main(String[] args){ //Simple primitive data type declarations byte byteNum = 125; System.out.println("The byte number is: " + byteNum); short shortNum = 32767; System.out.println("The short number is: " + shortNum); int intNum = -20; System.out.println("The integer is: " + intNum); } }
4.1.2 Overflow or underflow errors
Java throws a compilation error when the user-entered value is less than the minimum or more than the maximum value allowed. The example is for short but the same rules apply for the other data types as well.
KeywordsApp.java
public class KeywordsApp{ public static void main(String[] args){ //Simple primitive data type declarations // byte byteNum = 125; // System.out.println("The byte number is: " + byteNum); short shortNum = 32767; // System.out.println("The short number is: " + shortNum); //int intNum = -20; //System.out.println("The integer is: " + intNum); // Example for overflow error short shortSum = shortNum + 4; System.out.println("The sum is: " + shortSum); // Example of underflow short shortNum1 = -32767; short newShort = shortNum1-10; } }
4.1.3 Data type casting
We can convert from one primitive data type to another by casting to a bigger data type. For example, we can get a floating-point number after the division of two integers by casting it to float.
KeywordsApp.java
public class KeywordsApp{ public static void main(String[] args){ //Example fo transformation from one form to another. int number1 = 3027; int number2 = 100; System.out.println("By normal division : " + (number1/number2)); float div = (float) number1 / number2; System.out.println("The float division is: " + div); } }
4.2 Access modifiers
Access modifiers are keywords that Java uses to determine the scope or visibility. Access Modifiers can be used for classes, methods, and variables. There are many access modifiers but here we will look at the 2 most used access modifiers: private and public.
A public modifier enables the class or variable or method to be accessible from anywhere, even across packages. Private is the most restrictive modifier. When something is marked private it cannot be accessed from anywhere else except where it is written.
4.2.1 Public and private class
The first package: testPackages1 has 2 classes, one public and one private. As a rule in Java, there can be only one public class in one .java file and it has to have the same name as the file. There is also another private class named HelperClass and a default class HelperClass2.
AccessKeywords.java
package testPackage1; public class AccessKeywords { private class HelperClass { String nothingToDo =""; } //Can be accessed HelperClass hc = new HelperClass(); } class Helper2{ //cannot be accessed HelperClass hc = new HelperClass(); }
AccessKeywordsApp.java
package testPackage2; import testPackage1.AccessKeywords; public class AccessKeywordsApp { public static void main(String[] args) { //This can be accessed becuase class is public AccessKeywords aKeywords = new AccessKeywords(); //Private classes cannot be accessed HelperClass help = new HelperClass(); } }
Compilation of the above program leads to the following output:
• Fails compilation with errors in both AccessKeywords.java and AccessKeywordsApp.java
• The public class declaration does not have an error.
4.2.2 Public and private methods
The following example shows two methods one private and public. We try to access them in the other class, in the other package
AccessKeywords.java
package testPackage1; public class AccessKeywords { //Can be accessed only inside this class private int firstNum = 30; //can be accessed outside class and even package public char ch = 'A'; //Can be accessed only by this class private int multiplyBy2(){ return firstNum * 2; } //Can be accessed outside as well. public int sumNumbers(int num1){ return num1 + multiplyBy2(); } }
AccessKeywordsApp.java
package testPackage2; import testPackage1.AccessKeywords; public class AccessKeywordsApp { public static void main(String[] args) { //This can be accessed becuase class is public AccessKeywords aKeywords = new AccessKeywords(); //Access to public methods int result = aKeywords.sumNumbers(10); System.out.println("Result is: " + result); //Private methods cannot be accessed //aKeywords.multiplyBy2(); } }
When we try to access the multiplyBy2 method in the AccessKeywordsApp, it fails compilation. Once removed the program runs and executes without any issues since we can access all public methods from anywhere. The same rule applies for public and private variables.
4.3 Rest of the keywords
For looking at the rest of the keywords we will use a sample project called Library System. In this project, there is an option to View, Add, Edit and Search Books present in a fictional library.
The app has the following classes:
- ApplicationClass.java
- ApplicationConstants.java
- Book.java
- BookManager.java
ApplicationClass.java is the class where the application runs, while the BookManager.java has the bulk of the functionality. Given below is the code for the ApplicationClass.java, BookManager.java and a small snippet of the Book.java classes. The full code is available at the end of the article.
The javac command to compile the application is:
javac -cp lib/commons-io-sources.jar LibraryPackage/*.java
and to run
java -cp lib/*;. LibraryPackage/ApplicationClass
4.3.1 The code
The code for applicationClass.java and BookManager.java
ApplicationClass.java
package LibraryPackage; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class ApplicationClass { public static void main(String[] args) { BufferedReader input = new BufferedReader(new InputStreamReader(System.in)); BookManager bm = new BookManager(); String inputName = ""; while (true) { System.out.println("==== Book Manager ===="); System.out.println(" 1) View all Books"); System.out.println(" 2) Add a Book"); System.out.println(" 3) Edit a Book"); System.out.println(" 4) Search for a Book"); System.out.println(" 5) Exit"); System.out.println(""); System.out.print("Please choose from the options View, Add, Edit, Search or Exit:"); try { String str = input.readLine(); int choice = Options.getAction(str); switch (choice) { case 1: bm.viewAllBooks(); break; case 2: System.out.println("==== Add a Book ===="); bm.addBook(); break; case 3: System.out.println("==== Edit a Book ===="); bm.editBook(); break; case 4: System.out.println("Enter the name of the book to search:"); try { inputName = input.readLine(); if (!inputName.isEmpty()) { bm.searchBook(inputName); } } catch (IOException e) { e.printStackTrace(); } break; case 5: System.out.println("All changes saved!"); input.close(); System.exit(0); break; default: System.out.println("Invalid choice!Please pick an option from View, Add, Edit, Search or Exit "); break; } } catch (IOException e) { e.printStackTrace(); } } } public static enum Options{ VIEW(1), ADD(2), EDIT(3), SEARCH(4), EXIT(5); private int action; public static int getAction(String input){ int out = 0; Options[] values = Options.values(); for(Options val : values){ if(input.toUpperCase().contains(val.name())){ out = val.action; } } return out; } Options(int val){ action = val; } } }
BookManager.java
package LibraryPackage; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; import org.apache.commons.io.input.ReversedLinesFileReader; public class BookManager { ArrayList books = new ArrayList(); public void viewAllBooks() { loadAllBooks(); allBooksString(); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); while (true) { System.out.println("Please enter the ID of the book to see the details.Press Enter to exit "); String in = null; try { in = br.readLine(); if (in.isEmpty() || in.equals("")) { break; } else { int bookId = Integer.parseInt(in); for (Book bk : books) { if (bk.getId() == bookId) { displayBookDetail(bk); } } } } catch (IOException e) { e.printStackTrace(); } } } /** * The method adds a new book to the library. The title,author and description * is kept optional. If the user has not entered any details, then a space is * inserted in the file. */ public void addBook() { String csvFile = ApplicationConstants.LIB_NAME; // To get the latest id from the csv file File inputFile = new File(csvFile); Book bk = new Book(); try (ReversedLinesFileReader rf = new ReversedLinesFileReader(inputFile, Charset.defaultCharset()); FileWriter txtWriter = new FileWriter(ApplicationConstants.LIB_NAME, true);) { String line = rf.readLine(); if (line != null) { String[] lastLine = line.split(","); // Auto-increment the ID in the library bk.setId(Integer.parseInt(lastLine[0]) + 1); } else { bk.setId(1); } // Inputs from the user System.out.println("======Please Enter the following information:"); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); System.out.println("Title:"); String title = br.readLine(); if (!title.isEmpty()) { bk.setTitle(title); } else { bk.setTitle(" "); } System.out.println("Author:"); String author = br.readLine(); if (!author.isEmpty()) { bk.setAuthor(author); } else { bk.setAuthor(" "); } System.out.println("Description:"); String desc = br.readLine(); if (!desc.isEmpty()) { bk.setDescription(desc); } else { bk.setDescription(" "); } // Output or Save to file txtWriter.write("\n"); txtWriter.write(bookToString(bk)); System.out.println("Book [" + bk.getId() + "] Saved."); System.out.println("================================"); } catch (IOException e) { e.printStackTrace(); } } /** * This method is used to edit a file already in the Library. All the fields * except the ID can be changed. If the user does not change the detail of a * particular field, then the field is set to its old value. */ public void editBook() { // To show all the books in the Lib loadAllBooks(); allBooksString(); File f = new File(ApplicationConstants.LIB_NAME); BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); try { String newLine = ""; int index = -1; while (true) { System.out.println("Enter the book ID of the book you want to edit, to return press ."); String input = in.readLine(); if (input.isEmpty() || input.equals("")) { System.out.println("=================================="); break; } else { int bookId = Integer.parseInt(input); for (Book bk : books) { index++; if (bk.getId() == bookId) { System.out.println( "Input the following information. To leave a field unchanged, hit "); System.out.println("Title[" + bk.getTitle() + "] :"); String title = in.readLine(); if (!title.isEmpty()) { bk.setTitle(title); } System.out.println("Author[" + bk.getAuthor() + "] :"); String author = in.readLine(); if (!author.isEmpty()) { bk.setAuthor(author); } System.out.println("Description[" + bk.getDescription() + "] :"); String desc = in.readLine(); if (!desc.isEmpty()) { bk.setDescription(desc); } // this gives the line to be edited newLine = bookToString(bk); List lines = new ArrayList(); lines = Files.readAllLines(Paths.get(ApplicationConstants.LIB_NAME ),Charset.defaultCharset()); // add the edited line to the list lines.set(index, newLine); // overwrite the file FileWriter fw = new FileWriter(f); Boolean first = true; for (String line : lines) { // To ensure that there are no extra line separators if (!first) fw.write(System.lineSeparator()); else first = false; fw.write(line); } fw.close(); break; } } } } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } // Searched through the library for a book using the title of the book. public void searchBook(String inputName) { // To ensure that Search can be the first operation if (books.isEmpty()) { loadAllBooks(); } if (!books.isEmpty()) { System.out.println( "The following books matched your query. Enter the book ID to see more details, or to return."); for (Book bk : books) { // To ensure that any string irrespective of the capitalization will be searched if (bk.getTitle().toLowerCase().contains(inputName.toLowerCase())) { System.out.println(bookDetail(bk)); //break; } } while (true) { System.out.println("Please enter the ID of the book to see the details.Press Enter to exit "); String in = null; BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); try { in = br.readLine(); if (in.isEmpty() || in.equals("")) { System.out.println("=================================="); break; } else { int bookId = Integer.parseInt(in); for (Book bk : books) { if (bk.getId() == bookId) { displayBookDetail(bk); break; } } } } catch (IOException e) { e.printStackTrace(); } } } else { System.out.println("No books in the Library to search"); } } /* Util Functions */ private void displayBookDetail(Book bk) { System.out.println("=====Book Details======"); System.out.println("Book ID: " + bk.getId()); System.out.println("Title: " + bk.getTitle()); System.out.println("Author: " + bk.getAuthor()); System.out.println("Description: " + bk.getDescription()); System.out.println("==================================================="); } private String bookDetail(Book bk) { return "[" + bk.getId() + "] " + bk.getTitle(); } private void allBooksString() { if (!books.isEmpty()) { for (Book bk : books) { System.out.println("[" + bk.getId() + "] " + bk.getTitle()); } } else { System.out.println("No books to show!Please add books to the library"); } } // Format a book object to a string to be written to a file private String bookToString(Book b) { return b.getId() + "," + b.getTitle() + "," + b.getAuthor() + "," + b.getDescription(); } // Get all the books in the file and store in a collection private void loadAllBooks() { String txtFile = ApplicationConstants.LIB_NAME; String line = ""; String cvsSplitBy = ","; // Ensuring books do not reappear in the list books.clear(); try (BufferedReader br = new BufferedReader(new FileReader(txtFile));) { while ((line = br.readLine()) != null) { // use comma as separator String[] book = line.split(cvsSplitBy); Book bk = new Book(); if (book != null) { bk.setId(Integer.parseInt(book[0])); if (book[1] != null || !book[1].equals("") || !book[1].isEmpty()) { bk.setTitle(book[1]); } else { bk.setTitle(" "); } if (book[2] != null || !book[2].equals("") || !book[2].isEmpty()) { bk.setAuthor(book[2]); } else { bk.setAuthor(" "); } if (book[3] != null || !book[3].equals("") || !book[3].isEmpty()) { bk.setDescription(book[3]); } else { bk.setDescription(" "); } books.add(bk); } } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
4.3.2 Keywords seen
The above files have most of the important Java keywords. For example, in the ApplicationClass.java file, we see the keywords
- package
- Import
- Try
- catch
- enum
- while
- switch
- default
- case
- break
The BookManager file shows how to use
- if
- else
- for
- while
The Book.java file has the super and this keywords used.
Some screens of the application are as follows:
5. Summary
In this article, we looked at Java keywords, their usage, and categories. We saw how to use Java keywords and how they interact with each other through an app. Java Keywords are essential to Java and are we use them in almost every single line of code as seen in the above examples. They are the “Nuts and Bolts” of Java.
6. Download the Source Code
This was a tutorial on Java Keywords, the nuts and bolts of Java.
You can download the full source code of this example here: Java Keywords Tutorial