Learn different keywords in Java and its implementaions

1
2316
  • In this tutorial we will learn different keywords in java and its implementations where we will have brief description of each and every keyword used in java language explained with examples.
    • To learn different keywords in java and its implementations follow the steps given below :

    1. Java has keywords which are enum, abstract, boolean, char, int, float, byte, case, break, finally, default, do, if, else, for, continue, while, switch, short, long, return, double, private, public, protected, package, try, catch, throw, throws, void, const, this, super, static, synchronized, new, implement, instanceof, extend, class, volatile, transient, strictfp, assert, native, interface, import.
    2. Reserved Keywords : true, false, null, goto
    3. Here is the explanation of the keywords :
      1. abstract: – An abstract class & method is declared with keyword abstract. In this scenario abstract class can be extended but cannot be instantiated. In this case if a subclass of an abstract class does not implement the abstract methods of its superclass, subclass is also abstract.
      2. Syntax :

        public abstract class MyDemo
        {
        }
        
        

        Example : This example shows the use of abstract keyword

        abstract class J //declare class as abstract
        {
        abstract void display(); //define method
        }
        class K extends J     //create class and extend it with abstract class
        {
        void display()   //declare method
        {
        System.out.println ("This is abstract program!"); //print statement
        }
        public static void main (String[] args) //main method
        {	
        K k = new K ();  //create object
        k.display ();   //call method
        }
        }
        

        Output :

        This is abstract program!

      3. boolean: – A boolean variable indicate values only true or false. A boolean may not convert into numeric values. This is primitive data type. Default value is false.
      4. Syntax :

        boolean val = true;
        if (val)
        {  
            //statement
        } 
        

        Example : This example shows the use of boolean keyword

        public class JavaBlnSample {
        public static void main (String [] args) //main method
        {
        //create an boolean object from boolean value
        Boolean Ob1 = new Boolean (true); 
        {
        /*create an boolean object from string.
        It show true if the string is not null else shows false*/
        Boolean Ob2 = new Boolean ("false");
        //print value of boolean object from string
        System.out.println (Ob1);
        System.out.println (Ob2);
        }
        }
        }
        

        Output :

         true
         false
        

      5. char: – A char variable used for storing a single Unicode character. This char keyword is used to declare method return value of type character. It has 16 bit size.
        \ ” − double quote
        \ – backslash.
        \f − form feed
        \’ − single quote
        \n − newline
        \b – backspace

      6. Example : This Java Example shows how to declare and use Java primitive char variable inside a java class.

        public class Char 
        {
        //create class 
        public static void main(String[] args) //main method
        {
        //define char variables
        char c1 = 'p';
        char c2 = 80;
        //below statements print the output of ASCII value of 80 
        System.out.println ("Value of char variable c1 is:" + c1);
        //ASCII code of 'P'
        System.out.println ("Value of char variable c1 is:" + c2);
        }
        }
        

        Output :

        Value of char variable c1 is: p
        Value of char variable c1 is: P
        

      7. int : – It defines constants MIN_VALUE and MAX_VALUE which represents the range of values for int type.
        int values are negative, positive or may be zero.
      8. Example : This Java Example shows how to declare and use Java primitive
        int variable inside a java class.

        public class Int  {
        public static void main(String[] args) {
        // here assigning default value is optional.
        //declare integer a and b
        int a = 16; 
        int b = 101;
        //print values of variable a and b
        System.out.println ("Value of int variable i is:" + a);
        System.out.println ("Value of int variable j is:" + b);
        }}
        

        Output :

        Value of int variable i is: 16
        Value of int variable j is: 101
        

      9. float : – This is java primitive type, Size is 32 bits. Its default value is 0.0
      10. Example : This Java Example shows how to declare and use Java primitive float variable inside a java class.

        public class Float
        {
        public static void main(String[] args) {
        float f = 14.3f;//declare float value
        System.out.println ("Value of float variable f is:"+f); //print value
        }
        }
        

        Output :

        Value of float variable f is: 14.3

      11. byte : – byte size is 8 bit integer value. It can store integer value in the range -128 to 127.Default value is 0.
      12. Example : This Java Example shows how to declare and use Java primitive byte variable inside a java class.

        public class Byte {
        public static void main(String[] args) {
        //declare byte values to variable a and b
        byte a = 43;
        byte b = 14;
        //print values of a and b
        System.out.println ("Value of byte variable a is:" + a);
        System.out.println ("Value of byte variable b is:" + b);
        }
        }
        

        Output :

        Value of byte variable a is: 43
        Value of byte variable b is: 14
        

      13. short : – Size of the short data type is 16 bit. Its min value is -32,768 and max value is 32,767. It is a java primitive data type. In this case default value is 0. A short is two times as small as int.
      14. Example : This example shows how short is used in a program.

        public class Short  {
        public static void main(String[] args) {
        //declare short values to variable i and j
        short i = 18;
        short j = 35;
        //print values of i and j
        System.out.println ("Value of short variable i is:" + i);
        System.out.println ("Value of short variable j is:" + j);
        }}
        

        Output :

        Value of short variable i is: 18
        Value of short variable j is: 35
        

      15. long : – This is a java primitive type. Size of long data type is 64 bit. Minimum value is -2^63 and maximum value is 2^63-1. In this case default value is 0L. This type is used when large range than int is needed.
      16. Example : This example shows how an object of Long can be declared and used.

        public class LongProgram {
        public static void main(String[] args) {
        //Create a Long object from long
        long l = 46;
        Long lObj = new Long (l);
        //print value of Long objects
        System.out.println (lObj);
        }
        }
        

        Output :

        46

      17. double : – This is a java primitive type. It may store floating point value. The size is 64 bit float primitive type.
      18. Example : This example shows how to use double in a class.

        public class JavaDouble 
        {
        public static void main(String[] args)
        {
        double d = 1643.43//declare value of double with variable d
        // print value of double
        System.out.println ("Value of double variable d is:" + d);               
        }
        }
        

        Output :

        1643.43

      19. break : – The break keyword is used to exit a for loop, while loop, do loop or to the end of a case block in a switch statement.
      20. Example : This Java Example shows how to break the loop or condition in a class.

        public class Break{
        public static void main(String[] args){
        int j,k;
        System.out.println ("Numbers between 1 to 8 :");
        /*check j is less than 8 then it increment 
        with 1 and go to next loop and check k is 
        less than j then go to if loop addition of 
        j and k equal to 6*/
        for (j  = 1; j < 8; j++) {
        for (k = 2; k <j; k++) {
        if (j+k==6)
        {
        break;
        }//break if condition is false
        }
        if (j==k)
        {
        //check j equal to k if yes then print j
        System.out.println (" "+j);
        }
        }
        }
        }
        

        Output :

        Numbers between 1 to 8:
         2
         3
         5
         6
         7
        

      21. continue : – Continue is helpful for skipping the next iteration of a do, while or for loop statement.
      22. Example : This example shows how to use java continue statement to skip the iteration of the loop.

        public class Continue 
        {
        public static void main(String args[]) {
        //use array to declare integer
        int [] num = {1,14,9,16,5,7};
        for(int a : num ) {//store num values in int a
        //check if a equals to 16 then skip 16 and print next values
        if( a == 16 ) {
        continue ;}//skip 16 and continue iteration 
        System.out.println (a); //print statement
        System.out.println ("\n");
        }
        }
        }
        

        Output :

        1
        14
        9
        5
        7
        

      23. try, catch, finally : –
        try block is used for throwing the exception. Every try block must have one or more catch blocks or finally block.

        catch keyword is used for catching the exception which is thrown from the try block. Each catch block handles the various types of exceptions.

        finally keyword is used to define a block that is always executed in a series try, catch, finally statement. Every try block must have at least one catch or finally block. When try block is executed after that the code of finally block must be executed with or without exception, if any problem occur during execution in the catch block then also finally block must be executed at least once.

      24. Example : This Java Example shows how to use try catch and finally in a class.

        public class Try 
        {
        public static void main(String args[])
        {
        int a=10;
        int b=5;
        try //throws the exception
        {
        int x=a/(b-b);      //Exception here
        }
        catch (ArithmeticException e)//catch the exception
        {
        System.out.println ("Division by zero");
        }
        
        finally //finally block
        {
        int y=a/b;
        System.out.println ("y = "+y); //print output
        }
        }
        }
        

        Output :

        Division by zero
        y = 2
        

      25. do : – do loop body is always executed at least once. Semicolon is always required after the conditional expression.
      26. do keyword
        Example : This Java Example shows how to use do while loop to iterate in Java program.

        public class DoWhile {		 
        public static void main(String[] args) {
        //In this case the condition is checked after executing the loop body.
        //So loop will be executed at least once even if the condition is false.
        int a =0;  //declare int value in variable i
        do
        {
        //start do loop
        System.out.println ("a is : " + a);//print a
        a++;//increment a by 1
        //if the condition is false then execute while loop
        }while(a < 4);
        }
        }
        

        Output :

        a is: 0
        a is: 1
        a is: 2
        a is: 3
        

      27. while : - This keyword is indicates that the loop is executed continuously till condition is true.
      28. While Keyword

        Example : This example shows how while keyword is used in a class.

        public class While {//create class 
        public static void main(String args[]){//main method
        int num = 16; //define integer num
        while (num < 20)
        {
        /*check condition num is greater than define integer or not if
        true then print num*/
        System.out.println ("Value of num:" + num); //print statement
        num ++;
        }
        }//num increment by one
        

        Output :

        Value of num: 16
        Value of num: 17
        Value of num: 18
        Value of num: 19
        

      29. if - else : -
        if “is used for executing logical statements or conditional statements. An if statement has else block which is optional containing the code that is executed if the condition is false.

        else keyword is always used with the “if” keyword. The else block is optional and this block is executed when if condition is false.
      30. If statement
        Example : This example shows how if-else statement used in a class.

        public class If-Else 
        {
        public static void main (String [] args)//main method
        {
        int a = 16;
        if (a > 100)//check the condition a is greater than 100
        System.out.println ("a is greater than 100"); //print statement
        else if (a > 50)//else if a is greater than 50
        System.out.println ("a is greater than 50"); //print statement
        else
        System.out.println ("a is less than 50"); //else print statement
        System.out.println ("a="+a);
        }
        }
        

        Output :

        a is less than 50
        a=16
        

      31. switch, case, default : -
        The switch keyword is used to select execution of one of various code blocks based on expression or condition. To exit the switch statement, break statement must be included at the end of the block.

        case does not have an implicit ending point. A break keyword must typically used at the end of each case block to exit the switch statement. Without a break statement, the flow of execution will flow into all defined cases and last follow default block.

        default is access modifier, when we don’t use any access modifier then by default it is treated as default access modifier. And it can access only within package this is used in the switch cases. It will execute if none of the defined cases are matched to the condition.
      32. Example : This example shows how to use switch-case and default in a class.

        class Switch{ //create class switch
        public static void main(String[] args) {//main method
        int day =4;//accessing the 4th day of the week
        switch (day) {//day will switch to the 4th case
        //we uses break keyword to break the cases if true
        case 1:  System.out.println("Monday"); break;
        case 2:  System.out.println("Tuesday"); break;
        case 3:  System.out.println("Wednesday"); break;
        case 4:  System.out.println("Thursday"); break;
        case 5:  System.out.println("Friday"); break;
        case 6:  System.out.println("Saturday"); break;
        //if we don’t specify day then it will print Sunday
        default:  System.out.println("Sunday"); break;
        }
        }
        }
        

        Output :

        Thursday

      33. void, return : -

        When method does not return any type of value that time void keyword is used. This void keyword in the programming language returns the null value.

        The return keyword returns a value. The parentheses are optional surrounding the return value.
      34. Example : This example shows how to write void and return in a class.

        public class Return 
        {
        //declare integer with static
        static int a=5;
        static int b=11;
        public static void main(String[] args)//void is used 
        {
        System.out.println (a+b); //addition of a and b
        return;//return give addition of a and b
        }
        }
        

        Output :

        16

      35. private : - This keyword is access control modifier. This is applied to a method or a field. It can also apply to a constructor. This is a most restrictive level than access modifier. When we declare a method or variable and a constructor as a private then that a method or a variable and a constructor cannot access outside the class.
      36. Example :

        private void method ();

      37. public : -This public keyword is used to declare a class, a method or a field public, that means this methods or a field can access anywhere like within same class, within same package, outside package in subclass and outside package. This is the lowest restrictive level.
      38. Example : This example shows how to use public a class.

        //Save with class First
        public class First{  //create class First
        public void msg(){
        System.out.println ("This is Public modifier");
        }   
        }  
        
        //Save with class Second
        
        package Topic;//create new package
        import Topic1.*;//import package Topic1
        class Second//create class Second
        {
        public static void main(String args[]){//main method  
        First obj = new First (); //create object of class First
        obj.msg (); //call method of class First
        }
        }
        

        Output :

        This is Public modifier

      39. protected : -This access modifier is accessible in within class, within package and within outside package by subclass only. Not accessible in outside package.
      40. Example : This example shows how to use protected in a class.

        //In same project create a new class save by First.java  
          
        public class First//create class First
        {
        protected void msg()
        {
        //declare method as protected
        System.out.println ("This is protected") ;}} //print statement.
        
        // In same project create another calss and save by Second.java  
        
        
        class Second extends First//extends class First
        { 
        public static void main(String args[]){  //main method
        Second obj = new Second (); //create object of class Second 
        obj.msg () ;
        }
        }
        

        Output :

        This is protected

        protected keyword

      41. package : - package keyword is used for declaring a java package. When source file does not containing a package statement that time classes defined in the file are in the default package.
      42. Example :

        package com.mypack
        public class MyFavourite
        {
        }
        

      43. throw : - This keyword is used for explicitly throwing exception. throw keyword is used within the method. We cannot throw multiple exceptions at a time. throw keyword is used with checked as well as unchecked exceptions.
      44. throws : - This throws keyword is used with only checked exception. throws is declare with method definition.
      45. const : - This keyword const is used in java for defining a constant. If you declaring any variable const then after you cannot alter that variable.
      46. this : - this is used to refer the current object. When ambiguity occur between parameter and instance variable then this keyword resolve this type of problem. This is a special keyword in java.
      47. super : - super is special keyword in java. Super keyword is used inside the sub-class. Through super keyword only public and protected methods are called.
      48. new : - new keyword is used to create array object or instance of a class. This new keyword is used for allocates memory dynamically. You can also used new keyword for creating simple java object.
      49. static : - Static variables are known as global variables or class variables. When you define variable as a static then there will be only one copy of that static variables created into JVM memory. This static variable shares only one copy throughout the class of instances. In java, static keyword is used for memory management. static variables are helpful to save memory.
      50. Example : This example shows how to use static and new in a class.

        public class Stud  // create class
        {
        int rolno;		//define integer
        String name;		//define string
        String address;		
        static String division = "A";	//define static variable
        //define constructor with parameters
        Stud (int rn, String nm, String adds) 	
        {
        rolno = rn; 
        name = nm;
        address = adds;
        }
        void display()		//method declaration
        {
        System.out.println (rolno+"  "+name+" "+address+" "+division);
        }
        public static void main(String[] args) 	//start execution
        {
        //create object with new keyword
        Stud s1 = new Stud (101, "Pooja", "Vashi");
        Stud s2 = new Stud (102, "Shilpa", "Sanpada");
        s1.display (); 	//call method
        s2.display ();	//call method
        }
        }
        

        Output:

        101 Pooja Vashi A
        102 Shilpa Sanpada A
        

      51. extend : - This extend keyword is used in a class declaration to define the superclass. Also used in an interface declaration to define one or more super interfaces. At a time a class may only extend one other class. In inheritance process of java extend keyword is used. It means it adds the method and variables of that extended class.
      52. Example : This example shows how to use extend in a class.

        //In same project create two classes save the first class as ParentEX
        public class ParentEx
        {
        public String n1 = null;
        public String n2 = null;//define string
        
        public void printOut()//declare method
        {
        System.out.println ("Output of First:"+n1);
        System.out.println ("Output of Second:"+n2);
        }
        }
        //In the same project create new class and save it as ChildEx
        
        public class ChildEx extends ParentEx //extends a parent class
        {
        public void parentMeth()
        {
        n1="Hi this is First";
        n2="This is Second class where extends used";
        printOut ();
        }
        public static void main (String[] args) 
        {
        ChildEx ce = new ChildEx (); //object creation
        ce.parentMeth (); //call method
        }
        }
        

        Output :

        Output of First: Hi this is First
        Output of Second: This is Second class where extends used
        

      53. class : - class keyword is used to define a class. Class completed with curly braces and within that curly braces variables, methods are declared.
      54. Example :

        class MyHome //create class
        {	
        int num; //define integer
        void display()//declare method
        {
        System.out.println (“num”) ;
        }//print statement
        }
        

        Output :

        num

      55. import : - Import keyword is used in java to import user defined and built-in packages into java source file. So it will help you as your class can refer to a class that is into another package, by using its name.
      56. implement : - This implement keyword is used to declare the interfaces that are to be implemented by the class. This is used in class definition. One class may implement multiple interfaces. implement keyword is used for inheritance. implement keyword support to the multiple inheritances.
      57. interface : - When you declare a special type of class that class body contains only constant fields, static interfaces and abstract methods. Using interface keyword interfaces are declared. It cannot be instantiated, but implemented.
      58. synchronized : - This keyword is used for a method can accessed by only one thread at a time. It can be applied only to a method, not on a variables or classes.
      59. volatile : - In this case you can specify member variable that variable may be modified asynchronously by more than one thread. This keyword may not be implemented in many JVM.
      60. instanceof : - This keyword is used to determine the class of an object. It produces a boolean result.
      61. Example :

        class Maml implements Ani
        { }
        
        class Cat extends Maml
        {
        public static void main (String [] args)
        {
        Maml m = new Maml (); //create object of maml
        Cat c = new Cat (); //create object of cat
        //use instanceof produce boolean result
        System.out.println (m instanceof Ani);
        System.out.println(c instanceof Maml);
        System.out.println(c instanceof Ani);
        }
        }
        

        Output :

        true
        true
        true
        

      62. transient : - This can only be applied to fields or member variable. Transient variable is not saved when an object gets serialized. This is used to provide you some control over serialization process and gives you flexibility to exclude some of object properties from serialization process.
      63. strictfp : - For floating-point calculation use this strictfp keyword which ensures portability i.e. platform independent. This is used with class and variables only. When you want the answer from your code, then you need to declare the strictfp modifier.
      64. assert : - You can define assert statement with the help of assert keyword. It is used to test your assumptions about the program. While executing assertion, it is consider being true. If it fails, JVM will throw an error named AssertionError. It is mainly used for testing purpose.
      65. native : - This keyword is only applied to methods, not variables or classes.
      66. enum : - This is a type whose field consists of a fixed value of constant. It extends parent class called as Enum. It can implement interfaces. Using new operator we cannot create instance of enum. In java constructor of enum is always private. Constants of enum are implicitly final and static.
      67. for : - It is a pretest loop statement. In this case initialization and increment is an expression. A boolean expression also is an expression that can be true or false. In this case when loop is executed then first initialization expression is evaluated. This expression assigns the initial value to loop control variable (eg. j=1). The boolean expression is tested start of the each iteration of the loop. The loop terminates when it is false and expression is frequently a comparison (j<=10). After that increment expression is evaluated, that can increment the control variable (eg. j++).
      68. Example : This example shows how to use for loop in a class.

        public class ForLoop
        {
        public static void main(String[] args) {
        // Initialization is executed only once.
        //loop is executed till condition is true
        for(int num = 0; num <= 2 ; num++)
        //print the num value
        System.out.println ("Number is : " + num);
        }
        }
        

        Output :

        Number is : 0
        Number is : 1
        Number is : 2

    4. Explanation of Reserved Keywords :
      1. true: - This returns a boolean result which is true only.
      2. false : - This returns a boolean result which is false only.
      3. null : - This reserved keyword represents no value. Primitive type of variables null cannot be assigned like (boolean, byte, char, double, float, int, long, short).
      4. goto : - This goto keyword is used to jump to the respective line of code or execute a particular segment of code.
    5. Hence, we have successfully learnt different keywords in java and its implementations .

    1 COMMENT

    LEAVE A REPLY

    Please enter your comment!
    Please enter your name here