Java Keywords
Keywords as per define reserved word by compiler, this are used to special meaning and purpose. We can't define the name of identified by keywords. Here include all list of Java programming keywords.
List of java keywords
There is following keywords are generally used in java programming language. Which is use to declare statement, class function, data type, control mechanism etc.
abstract | assert | boolean | break |
byte | case | char | catch |
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 |
static | strictfp | super | switch |
synchronized | this | throw | throws |
try | void | volatile | while |
In this list const and goto are not used currently. In this post we are learning about, how to use those keywords and what is the purpose of those keywords.
Primitive data type
primitive data type are used to declare a variable in our program. so that is important we are how to use those data type in our program. Here given one basic example to declare and use primitive data types.
// Example of Primitive Data Types
public class PrimitiveTypes
{
public static void main(String[] args)
{
// Declare Primitive data type
byte age = 100;
short hourlyCharge = 30000;
char alphabetChar = 'A';
float profit = 67.24f;
double monthlySalary = 423524.21;
long population = 8388592;
int citys = 1000;
boolean status = true;
// Use variable value
System.out.printf(" Population : %s", population);
}
}
Output
Population : 8388592
void and return
void are used to defining return data type of a function. If function are not return any value then void keyword are used.
return is another keyword that are normally used in returning a value by function. And also used to execute back to previous execute function.
// Example return and void keyword
public class Test
{
int numOne;
int numTwo;
String name;
Test(int numOne, int numTwo, String name)
{
this.numOne = numOne;
this.numTwo = numTwo;
this.name = name;
}
int sum()
{
return numOne + numTwo; // return result
}
// void are used to define return type of function
// This function are display value but not return any value
void displayName()
{
System.out.println(" Hello " + name);
}
void checkInfo()
{
System.out.println(" Back to Main ");
boolean status = true;
if (status == true)
{
return; // Without return value
}
// This statement are not work
System.out.println(" Error in This Code ");
}
public static void main(String[] args)
{
Test obj = new Test(2, 5, "Smith");
int result = obj.sum();
obj.displayName();
System.out.println(" Result : " + result);
obj.checkInfo();
}
}
Output
Hello Smith
Result : 7
Back to Main
abstract and extends keyword in java
abstract keyword are used to define abstract class and abstract methods. Abstract method of abstract class must be implemented by all inherit subclass (child class). And abstract class are provide function prototype of abstract method.
extends keyword are used to inherit one class properties into another class. In below example class B are inherited the properties of class A.
// Define abstract class
abstract class A
{
// Define abstract method
abstract void info();
// Implementing non-abstract method
void details()
{
System.out.println("This is Class A details function");
}
}
// Inherited the properties of base class A
public class B extends A
{
// Implementing abstract method
void info()
{
System.out.println("Class B are implementing abstract method of class A");
}
public static void main(String[] args)
{
B obj = new B();
obj.info();
obj.details();
}
}
Output
Class B are implementing abstract method of class A
This is Class A details function
Note that abstract and non-abstract (simple) method can be define within the abstract class. abstract methods are overridden by inherited subclass. And abstract class cannot instantiate objects.
assert keyword in java
assert is keywords that are used to check correctness of specified condition. When condition are false then that are produce an exception. This exception message are provide by programmer. This is very useful to check expression. And JVM are produce this exception. There syntax as follows.
assert (expression): "Exception Message";
For example
// Assertions example in java programming
public class Voting
{
public static void main(String[] args)
{
int age = 16;
// Check that voter age is valid or not
// Work when condition fail
assert age >= 18: "Invalid age to vote";
System.out.println("Age : " + age);
}
}
Compilation: javac Voting.java
run: java -ea Voting
//note that Voting.java file name
Output
Exception in thread "main" java.lang.AssertionError: Invalid age to vote
Note that, Assertion is by default disabled. View how to Enabling and Disabling Assertions. And we are executing program like following manner.
boolean keyword in java
boolean keyword are used to define boolean type variable that are contain primitive type boolean values like true and false.
// boolean keyword example
public class Program
{
public static void main(String[] arges)
{
boolean errorStatus = true;
if (errorStatus)
{
// When errorStatus is true
System.out.println("Error Found");
}
else
{
System.out.println("No Error found");
}
}
}
Output
Error Found
Note that most of expression are produced boolean result.
break keyword in java
Break are using inside the loops. That are used to terminate execution of looping statement.
// Break examples
public class Program
{
public static void main(String[] arges)
{
System.out.println(" Start Loop ");
// Execute loop in the range of 1..8
for (int i = 1; i < 8; i++)
{
// Display value
System.out.println(i);
if (i == 5)
{
// When i == 5 then
// terminate loop
break;
}
}
System.out.println(" End Loop ");
}
}
Output
Start Loop
1
2
3
4
5
End Loop
In this loop are normally execute looping statement statement in 7 times but when brake are terminated loop statement after 5th iteration. So we can use break normally and under the specified condition to terminate loop statement. And that is also used in switch statement.
Loop keyword (for, while, do while)
Normally three type of loop supported in java programming. For-loop while-loop and do-while loop.
for loop : for keyword are used to declare a for loop. There are declared as in follows.
for(initialization;condition;increment/decrement){
//loop statements
}
For example printing the number between 1 to 5.
// For loop example
public class LoopExample
{
public static void main(String[] args)
{
for (int i = 1; i <= 5; i++)
{
// Loop statement Here
// Display value
System.out.print(" " + i);
}
}
}
Output
1 2 3 4 5
while loop: while keyword are used to define while-loop statement. This statement are based on boolean result, when given expression are produce true boolean result then while-loop statements are work. Otherwise terminates loop execution.
while(test-expression){
//loop statement
}
This loop are mainly used when there is initial not decide how many number of times loop statement are executing. Another example printing node value of linked list. For example displaying Five Even numbers.
// While loop example
public class LoopExample
{
public static void main(String[] args)
{
int data = 2, counter = 1;
// Execute the loop until counter value is less than 6
while (counter <= 5)
{
if (data % 2 == 0)
{
System.out.print(" " + data);
counter++;
}
// Increase the data value by one
data++;
}
}
}
Output
2 4 6 8 10
do-while loop: This loop is first execute loop statement and after that checking its terminating condition. This are provide a guarantee to execute loop at least one time.
// import package for Scanner class
import java.util.Scanner;
// Example of do-while loop
public class DoWhile
{
public static void main(String[] args)
{
// Make object of scanner class
Scanner action = new Scanner(System.in);
String status = "no";
do {
// Loop Statement
System.out.println("Eat food");
System.out.print("Are you still hungry ? (yes/ no) : ");
status = action.nextLine();
} while (status.equals("Yes") || status.equals("yes"));
}
}
Output
Eat food
Are you still hungry ? (yes/ no) : yes
Eat food
Are you still hungry ? (yes/ no) : yes
Eat food
Are you still hungry ? (yes/ no) : no
switch case default keyword
Switch case are used to check multiple test case of single value and pattern. Inside the body of switch define test condition. If condition is match by given expression then executed case block statements will work and terminate by break statement.
/*
Switch case statement example
*/
public class Example
{
static void caseStatement(String data)
{
// Expression variable
switch (data)
{
// Define case
case "One":
System.out.println("Case One");
// break switch
break;
case "Two":
System.out.println("Case Two");
// break switch
break;
case "Three":
System.out.println("Case Three");
// break switch
break;
default:
// When have no suitable case then this statement work
System.out.println("Default statement");
}
}
public static void main(String[] args)
{
// Test
caseStatement("Five"); //Execute default statement
caseStatement("Three"); //Execute case value three
}
}
Output
Default statement
Case Three
instanceof keyword
instanceof keyword are used to check belong of two objects are similar class.
// Example instanceof in java
// Define class
class Employee
{}
class Manager
{}
class SalesManager
{}
public class Test
{
static void typeCheck(Object obj)
{
if (obj instanceof Manager)
{
// When given obj is instance of Manager
System.out.println("This is an Manager");
}
else if (obj instanceof Employee)
{
// When given obj is instance of Employee
System.out.println("This is an Employee");
}
else if (obj instanceof SalesManager)
{
// When given obj is instance of SalesManager
System.out.println("This is an SalesManager");
}
else
{
System.out.println("Who are you ?");
}
}
public static void main(String[] args)
{
// Create objects
Employee employee = new Employee();
Manager manager = new Manager();
SalesManager salesManager = new SalesManager();
// Test
typeCheck(manager);
typeCheck(employee);
typeCheck(salesManager);
typeCheck("Hi");
}
}
This is an Manager
This is an Employee
This is an SalesManager
Who are you ?
import keyword
This keyword are used to importing a class which is define within a package. When importing a class that means we can access its variables and methods which is depends upon access specifiers protection. We can also import particular static variable by this statement. See this example.
import static java.lang.Math.PI;
class Test
{
public static void main(String[] args)
{
// PI is define within java.lang.Math
System.out.println("PI : " + PI);
}
}
PI : 3.141592653589793
static keyword
static keyword can be used to define function, inner class and variable.
static variable : Static variable are share single copy of all instance variable. In java programming static variable are declare at class level.
class Test
{
public static int x = 0;
public void check(int value)
{
// Change static variable value
x += value;
}
public static void main(String[] args)
{
Test a = new Test();
Test b = new Test();
// Add one
a.check(1);
// Add two
b.check(2);
// Note a and b is two objects
// Which are updating a static variable
// Which is share by both objects (a,b)
System.out.println(" x : " + Test.x); //use static variable
}
}
x : 2
static method : Static methods are not dependent on objects. They can be execute without objects. This method are execute within the defined class or inherited class.
public class Test
{
public static void check()
{
System.out.println("static method execute");
}
public static void main(String[] args)
{
// Call static method
check();
}
}
static method execute
main() method of program is a static method which is by default execute when running program.
interface or implements keyword
Interface is like a container class, Which are contain method and properties. By default all method of interface are abstract method and they are implemented by other class that are use this interface. The main goal of interface is providing a availability to implement multiple inheritance capability.
// Define interface
interface TestInterface
{
// Interface properties variables
public int x = 100;
// Abstract method
public void message(String about);
}
// Implements TestInterface by DemoOne class
class DemoOne implements TestInterface
{
// Implements interface method
public void message(String about)
{
System.out.println(about);
// Use interface field value
System.out.println("x : " + x);
}
}
public class Test
{
public static void main(String[] args)
{
DemoOne info = new DemoOne();
info.message("Interface");
}
}
Interface
x : 100
implements: This keyword are use interface into class and implement abstract method.
public, private and protected keyword
This keyword is used to declare variable class and function of our program. This are provide control mechanism in outside the other class and within the class.
class Record
{
protected float mark;
// private variable
private boolean result;
// Constructor of class
public Record(float mark)
{
this.mark = mark;
if (mark > 33)
{
this.result = true;
}
else
{
this.result = false;
}
}
public boolean resultStatus()
{
// Ok return private variable value
return result;
}
private void updateMark(float mark)
{
this.mark = mark;
}
}
public class Test extends Record
{
public Test(float mark)
{
super(mark);
}
public static void main(String[] args)
{
// Create a object of Test
Test task = new Test(76.5f);
// Protected variables are accessed outside of inherit class
// Using objects
System.out.println(" Mark :" + task.mark); // 76.5
// Not access private variables using objects
// System.out.println("Mark :" +task.result);
// Not access private method using objects
// task.updateMark(80.5);
if (task.resultStatus())
{
System.out.println(" Result : Pass ");
}
else
{
System.out.println(" Result Fail ");
}
}
}
Mark :76.5
Result : Pass
Learn more about access specifiers in java. Such as scope and usability.
Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.
New Comment