Keywords in Java and their use

The list of keywords in Java and their use are:-

abstractbooleanbreakbytecase
catch charclasscontinuedefault
dodoubleelseextendsfalse
finalfinallyfloatforif
implementsimportinstanceofintinterface
longnativenewnullpackage
privateprotectedpublicreturnshort
staticsuperswitchsynchronizedthis
throwthrowstransienttruetry
voidvolatilewhile  

 

abstract :- abstract keyword  is comes from the abstraction in Java. It is a non-access modifier applies for classes and methods.

abstract class AbstractClass
{
    abstract void abstractMethod();
}

 

boolean :- It is called logical (boolean) variable. It is  used to control two variables that are true and false.

public class Boolean  {
    public static void main(String[] args) {

        // Test true and false booleans.
        boolean value = true;
        if (value) {
            System.out.println("Today is monday");
        }
        value = false;
        if (!value) {
            System.out.println("Today is sunday");
        }
    }
}

Output
Today is monday
Today is sunday

 

break :- The break  keyword is used to break the execution of a loop statement (for, while, switch-case) which is based on some condition. Execution continues with the first statement after the structure common  use of  break keyword is to break out early from a loop or to skip the remainder of a switch structure.  

public class Break {
   public static void main(String[] args) {
      
      for (int x = 1; x <= 10; ++x) {      
         if (x == 7) {
            break;
         }      
         System.out.println("The value of x is "  + x );
      }   
   }
}

Output
The value of x is 1
The value of x is 2
The value of x is 3
The value of x is 4
The value of x is 5
The value of x is 6

 

byte :- A byte  variable can control a numeric value in the range from -128 to 127. It is used to assert byte type variable.

public class TestingByte {

	public static void main(String[] args) {
		
		byte x = 100;
		System.out.println("The byte is " + x ); 
	}

}

Output
The byte is 100

 

case , switch :- The switch keyword and case keywords is used in the switch case statement it is used to handle an array of decision in which a specific variable or expression is tested for values it may acquire, and different action are taken. 

public class SwitchLanguage{
 public static void main(String args[]){
   int language=3;
   switch(language){
     case 0:
     System.out.println("Hindi");
     break;

     case 1:
     System.out.println("English");
     break;

     case 2:
     System.out.println("French");
     break;

     case 3:
     System.out.println("German");
     break;

     case 4:
     System.out.println("Italian");
     break;

     default:
     System.out.println("Not in the list");
     break;
 }
}
}

Output
German

 

catch :- The catch block handles the exceptions  send by the try block. It take one argument java.lang.exception.

public class TryAndCatch
{
 public static void main(String args[])
 {
  int x,y,z;
  try
  {
   x=10;
   y=190;
   z=y/x;
   System.out.println("This line will not be performed");
  }
  catch(ArithmeticException e)
  {
   System.out.println("Divided by zero");
  }
  System.out.println("After exception is handled");
 }
}

Output
This line will not be performed
After exception is handled

 

char :- A char represents a single character. It is used to declared a variable.

public char getZLetter() {
    return 'Z';
}

 

class :-  class keyword is used to declare a class or define a class. It is used with the constructor and used to refer to the current object of the constructor.

class ClassTest
{
    class TestInnerClass
    {
        //Inner Class
    }
}

 

continue:- The continue keyword, when executed in one of the iteration structures (for, while and do/while), skips the remaining statements in the body of the structure and handle with a test for the next iteration of the loop.

public class Continue {

   public static void main(String args[]){
	for (int i=0; i<=10; i++)
	{
           if (i==6)
           {
	      continue;
	   }

           System.out.print(i+" ");
	}
   }
}

Output
0 1 2 3 4 5 7 8 9 10

 

default :- default  keyword is also used in the switch-case statements and it is used to declare a  default value in Java annotation. We can be used to interface to introduce methods with implementation of Java 8 .

public class Switch{
public static void main(String[] args) {

int language = 8;
String langString;
switch (language) {
case 1:  langString = "Hindi.";
break;
case 2:  langString = "English";
break;
case 3:  langString = "Bengali";
break;
case 4:  langString = "Assamese.";
break;
case 5:  langString = "Telugu";
break;
case 6:  langString = "Gujarati";
break;
case 7:  langString = "Malayalam";
break;
default: langString = "Invalid language";
break;
}
System.out.println(langString);
}
}

Output
Invalid language

 

do :- do keyword is used in the control statement to declare a loop. The do-while loop test the loop continuation condition after the loop body is performed;therefore,  the loop body is always executed at least once. 

public class ClassDo
{
    public static void main(String[] args) 
    {
        int x = 210;
         
        int y = 720;
         
        do
        {
            x = x + y;
             
            y = y + 7;
             
            System.out.println("x = "+x);
             
            System.out.println("y = "+y);
             
        } while (x <= 200);
    }
}

Output
x = 930
y = 727

 

double :- This keyword is also used to declare that a method returns a value of the primitive type double . The double variable can hold very large (or small) numbers. ... The double variable is also used to control floating point values.

public class ClassDouble
{
    public static void main(String[] args) 
    {
        double num1 = 780.56;
         
        double num2 = 656.230;
         
        double num3 = num1 * num1;
         
        System.out.println("The number is " +num3);
    }
}

Output
The number is 609273.9136

 

else :- The else keyword specifies separate actions to be executed when the condition is true and when the condition is false.

public class ClassIfElse {

   public static void main(String args[]){
     int x=200;
     if( x < 100 ){
	System.out.println("The value of X is less than 100");
     }
     else {
	System.out.println("The value of X is greater than or equal 100");
     }
   }
}

Output
The value of X is greater than or equal 100

 

final :- The final keyword in Java is used to bound the user. We can use this keyword with variables, methods and also with classes.

public  class FinalValue{  
   //Blank final variable
   final int MIN_VALUE;
	 
   FinalValue(){
    MIN_VALUE=8;
   }
   void myNumber(){  
      System.out.println(MIN_VALUE);
   }  
   public static void main(String args[]){  
      FinalValue obj=new  FinalValue();  
      obj.myNumber();  
   }  
}

Output
8

 

finally :- In finally keyword the  exception is liberated  or not and liberated exception is taken or not, this block will be always executed.

// A Java program to demonstrate finally. 
public  class StudentInfo { 
    
    // This method will be called inside try-catch. 
    static void RollNo() 
    { 
        try { 
            System.out.println("Sam roll number is 6"); 
            throw new RuntimeException("demo"); 
        } 
        finally
        { 
            System.out.println("modification can take place"); 
        } 
    } 
  
   
    //  This method will be called outside try-catch. 
    static void DateOfBirth() 
    { 
        try { 
            System.out.println("John data of birth is 6 July"); 
            return; 
        } 
        finally
        { 
            System.out.println("It is constant"); 
        } 
    } 
  
    public static void main(String args[]) 
    { 
        try { 
            RollNo(); 
        } 
        catch (Exception e) { 
            System.out.println("Exception caught"); 
        } 
        DateOfBirth(); 
    } 
}

Output
Sam roll number is 6
modification can take place
Exception caught
John data of birth is 6 July
It is constant

 

float :- In Java, float keyword is used to store the 32 bit float primitive types. Floats are commonly used to calculate expressions that require single fractional accuracy. 

public class ClassFloat
{
    public static void main(String[] args) 
    {
        float num1 = 7898.2f;
         
        float num2 = 904.25f;
         
        float num3 = num2 * num1;
         
        System.out.println(num3);
    }
}

Output
7141947.5

 

for :-  The for keyword handle all the detail statements until a condition is true.

public class ClassFor
{
    public static void main(String[] args) 
    {
        for (int x = 0; x <= 7; x++)
        {
            System.out.println(x);
        }
    }
}

Output
0
1
2
3
4
5
6
7

 

if :-  the if  keyword is used in if  and if and else structure, it executes an indicated action only when the condition is true.

public class ClassIf {

   public static void main(String args[]){
      int num=150;
      if( num < 200 ){
	  
	  System.out.println("number is less than 200");
      }
   }
}

Output
number is less than 200

 

implements :-  implements  keyword is used to implement an interface in Java. You can implement as many interfaces as you would like.

interface ClassInterface
{
    void testMethod();
}
 
class ImpClass implements ClassInterface
{
    public void testMethod()
    {
        System.out.println("This is demo");
    }
}

 

import :-  The import  keyword helps the compiler locate the classes you intend to use. The compiler uses import to  identify and load classes required to compile  a Java program .

import javax.swing.JOptionPane;  //import class JOptionPane
import java.util.Arrays;
import java.util.Scanner;

 

instanceof :- It is a binary operator used to test if an object,and also known as type comparison operator because it compares the instance with type. If we apply the instanceof   operator with any variable that has a null value, it returns false.

class Test
{
     
}
 
public class ClassInstance
{
    public static void main(String[] args) 
    {
        Test a = new Test();
         
        if(a instanceof Test)
        {
            System.out.println("This return null value");
        }
    }
}

 

int :-  int is a primitive type which holds the 32 bit signed integer and the range is -2,147,483,648 .. 2,147,483,647.

public class Integer
{
    public static void main(String[] args) 
    {
        int num1 = 960;
         
        int num2 = 250;
         
        int num3 = num1 +  num2;
         
        System.out.println(num3);
    }
}

Output
1210

 

interface :- interface is similar to class. It is a collection of abstract methods  Interfaces are declared using the interface keyword, and may only enclose method signature and constant information.

interface ClassInterface 
{
    public default void defaultMethod() 
    {
        System.out.println("Interface Method");
    }
}

long :- long is a primitive type which holds the 64 bit signed integer It used to declare an expression, method return value, or a variable of type long integer.

public class Long
{
    public static void main(String[] args) 
    {
        long num1 = 960;
         
        long num2 = 250;
         
        long num3 = num1 *  num2;
         
        System.out.println(num3);
    }
}

Output
240000

 

native :- native keyword is used with a method to signify that a specific method is implemented in native code using Java Native Interfaces(JNI).  It points  a method, that it will be implemented in other languages, not in Java.

class ClassNative
{
    public native void testMethod(int i, double d, boolean B,);
}

 

new :- The new keyword is used for array creation. It creates the object. Initialization. The new operator is followed by a call to a constructor, which initializes the new object.

class Test
{
     
}
 
public class ClassNew
{
    public static void main(String[] args) 
    {
        Test a = new Test();
    }
}

 

package :- A Java package produces to  organizing Java classes into namespaces. It helps to handle  all the operations . Each package in Java has its different name and it arranges  its classes and interfaces into a separate namespace, or name group.

package pack;  
public class TestPackage{  
 public static void main(String args[]){  
    System.out.println("Welcome to the new package");  
   }  
}

Output
Welcome to the new package

 

private :- It is an access modifier. It is used  to declare a member of a class as private anything declared private cannot be seen outside of its class.

class Private{  
private int number=900;  
private void msg(){System.out.println("This is example");}  
}  
  
public class Test{  
 public static void main(String args[]){  
   Private obj=new Private();  
   System.out.println(obj.number);//Compile Time Error  
   obj.msg();//Compile Time Error  
   }  
}

Output
Test.java:10: error: number has private access in Private
System.out.println(obj.number);//Compile Time Error 

Test.java:11: error: msg() has private access in Private
obj.msg();//Compile Time Error

 

protected :-  protected members of a class are noticeable within the package only, but they can be inherited to any subclasses.

class Protected
{
   protected int i = 111;   
     
   protected void method()
    {
        
    }
}

 

public :- public keyword is declared class as a public. Anything declared in the  public can be accessed from anywhere.

package animal; 
public class Cow 
{ 
   public void moo() 
      { 
          System.out.println("moo moo"); 
      } 
} 
package human; 
import animal.*; 
class read 
{ 
    public static void main(String args[]) 
      { 
          Cow obj = new Cow ; 
          obj.display(); 
      } 
}

Output
moo moo

 

return :- return keyword is used to return the control back . It is used to exit from a method, with or without a value.

public class Return { 
  
    double NUM(double x, double y) 
    { 
        double sum = 10; 
        sum = (x + y) / 7.0; 
        // return statement below: 
        return sum; 
    } 
    public static void main(String[] args) 
    { 
        System.out.println(new Return().NUM(6.4, 3.9)); 
    } 
}

Output
1.4714285714285715

short :-  A short  value can hold a 16-bit integer number which ranges from -32,768 to 32,767.It is  used to declare primitive short type variables.

public short getLength() {
    return 2789;
}

 

static :- It is used for the memory management. It works with variables, methods, blocks and nested class. It shares the same variable or method of a given class we can access static  members of the class directly there is no need to instance  of a class.

public class StaticCircle{

    public static void main( String[] args ) {

        double radius = 2.6;
        double area = Math.PI * Math.pow(radius,6);
        System.out.println("Area of circle is " + area);

	}
}

Output
Area of circle is 970.4875324595903

super :- It is  reference  variable in Java used to access super class members inside a sub class.

class A
{
    int x;
     
    public A(int x) 
    {
        this.x = x;
    }
     
    void methodA()
    {
        System.out.println(x);
    }
}
 
class B extends A
{
    public B()
    {
        super(50);    //Calling super class constructor
    }
     
    void methodB()
    {
        System.out.println(super.x);    //accessing super class field
         
        super.methodA();    //Calling super class method
    }
}
public class MainClass
{
    public static void main(String[] args){
        B obj = new B();
        obj.methodB();
    }
}

Output
50
50

 

synchronized :- synchronized keyword is used to organize in Java. It can be used with methods or blocks, but not with the variables. This synchronization is implemented in Java with a concept called monitors. All synchronized blocks to organize on the equal object can only have one thread executing inside them at a time.

class ClassSyn
{
    synchronized void synchMethod()
    {
        
    }
     
    void testMethod()
    {
        synchronized (this) 
        {
            
        }
    }
}

this :- this  keyword is used  to return the current class instance.

public class Test {
	int variable = 34;
	public static void main(String args[]) {
		Test obj = new Test();
		obj.method(29);
		obj.method();
	}
	void method(int variable) {
		variable = 10;
		System.out.println("Instance variable :" + this.variable);
		System.out.println("Local variable :" + variable);
	}
	void method() {
		int variable = 30;
		System.out.println("Instance variable :" + this.variable);
		System.out.println("Local variable :" + variable);
	}
}

Output
Instance variable :34
Local variable :10
Instance variable :34
Local variable :30

throw :- The throw  keyword is mainly used to deliver procedure exceptions. It is used specially to deliver an exception from a method or any block of code.

public class ClassThrow
{
    public static void main(String[] args) 
    {
        try
        {   
           throw new NumberFormatException();
        }
        catch(Exception excep)
        {
            System.out.println(excep);
        }
    }
}

Output
java.lang.NumberFormatException

 

throws :- throws  helps the visitors of that method in handling that exception. It is used to specify the exceptions which the present method may deliver.

public class Test  
{ 
    public static void main(String[] args)throws InterruptedException 
    { 
        Thread.sleep(100); 
        System.out.println("devstudioonline.com"); 
    } 
}

Output
devstudioonline.com

 

transient :- transient  keyword is used in serialization. Serialization converts the object state to serial bytes. It is used to record, a member variable not to be serialized when it has continued to streams of bytes.

class Transient implements Serializable 
{ 
    // Making Id transient for login 
    private transient String Id; 
  
    transient int age; 
  
    // serialize other fields 
    private String name, email; 
     dob; 
}

 

void :- It is used to express method and interpretation to establish that the method does not return any type of value.

class Void
{
    void methodReturnsNothing()
    {
        
    }
}

 

volatile :- volatile will be written into or read from the main memory. It tells the compiler that the value of the variable may replace at any time-without any action being taken by the code the compiler finds convenient.

class Volatile
{
  private volatile int counter = 20;
}

 

while :- while keyword is used in the while loop. It specifies that an action is to be repeated while some condition remains true.

public class While
{
    public static void main(String[] args) 
    {
        int x = 10;
         
        while (x <= 50)
        {
            System.out.println(x);
             
            x = x + 10;
        }
    }
}

Output
10
20
30
40
50

Note

  • Both goto and const are reserved words in java but they are currently not used.
  •  true, false and null are not the keywords. They are literals in java.

 

 

 

 

 

 

Keywords: