What is Keyword in Programming?

Keywords are predefined or reserved words that have special meaning to the compiler. In this article, we will discuss about keywords in programming, its importance, and usage in different languages.

What is a Keyword?

A keyword is a reserved word in a programming language that has a predefined meaning and cannot be used for any other purpose, such as naming variables or functions. Keywords form the basic building blocks of a program’s syntax.

Importance of Keywords in Programming:

Keywords are essential because they define the structure and control flow of the program. They are part of the syntax that allows programmers to write understandable and maintainable code. Without keywords, programming languages would lack the necessary commands and structure to perform operations and control the logic.

Characteristics of Keywords:

  • Reserved: Cannot be used as identifiers (variable names, function names, etc.).
  • Case-sensitive: In languages like C, C++, Java, and Python, keywords are usually case-sensitive (e.g., if is different from IF).
  • Fixed meaning: Keywords have a fixed purpose and meaning defined by the language specification.

Types of Keywords:

  • Control Keywords: Used for control flow, such as if, else, while, for.
  • Data Type Keywords: Define data types, such as int, float, char.
  • Storage Class Keywords: Specify the storage duration and linkage, such as static, extern.
  • Access Modifiers: Define access levels for classes, variables, methods (e.g., public, private, protected in Java and C++).
  • Others: Keywords that don’t fall into the above categories but are essential for specific functionalities, like return, void, new.

Keywords in C:

Below is the list of keywords in C:

auto, break, case, char, const, continue, default, do, double, else, enum, extern, float, for, goto, if, int, long, register, return, short, signed, sizeof, static, struct, switch, typedef, union, unsigned, void, volatile, while

Example:

C
#include <stdio.h>

int main() {

  // auto keyword
  auto num = 10; 

  // char keyword
  char initial = 'A';

  // for keyword
  for (int i = 0; i < 3; i++) {
    printf("num = %d, initial = %c\n", num, initial);
  }

  // break keyword
  for(int i=0; i < 10; i++) {
      printf("%d ", i);
    if(i == 5)
      break;
  }
    
  return 0;
}

Output
num = 10, initial = A
num = 10, initial = A
num = 10, initial = A
0 1 2 3 4 5 

Keywords in C++:

Below is the list of keywords in C++:

asm, auto, bool, break, case, catch, char, class, const, const_cast, continue, default, delete, do, double, dynamic_cast, else, enum, explicit, export, extern, false, float, for, friend, goto, if, inline, int, long, mutable, namespace, new, operator, private, protected, public, register, reinterpret_cast, return, short, signed, sizeof, static, static_cast, struct, switch, template, this, throw, true, try, typedef, typeid, typename, union, unsigned, using, virtual, void, volatile, wchar_t, while

Example:

C++
#include <iostream>

using namespace std;

int main()
{

    // int, double, char, bool keywords
    int age = 30;
    double pi = 3.14159;
    char initial = 'B';
    bool isTrue = true;

    // if, else keywords
    if (age > 25) {
        cout << "You are eligible." << endl;
    }
    else {
        cout << "Not yet eligible." << endl;
    }

      // for keyword
    for (int i = 0; i < 5; i++) {
        cout << "Iteration " << i << endl;
    }

    // while keyword
    int count = 0;
    while (count < 3) {
        cout << "Count: " << count << endl;
        count++;
    }

    // Switch, case keywords
    switch (initial) {
    case 'A':
        cout << "Initial is A" << endl;
        break;
    case 'B':
        cout << "Initial is B" << endl;
        break;
    default:
        cout << "Initial is something else" << endl;
    }


    return 0;
}

Output
You are eligible.
Iteration 0
Iteration 1
Iteration 2
Iteration 3
Iteration 4
Count: 0
Count: 1
Count: 2
Initial is B

Keywords in Java:

Below is the list of keywords in Java:

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, null, package, private, protected, public, return, short, static, strictfp, super, switch, synchronized, this, throw, throws, transient, try, void, volatile, while

Example:

Java
/*package whatever //do not write package name here */

import java.io.*;

class GFG {
    public static void main(String[] args)
    {
        // int, char, double, float
        int age = 25;
        char initial = 'J';
        double pi = 3.14159;
        float discount = 0.1f; 

        // break keyword
        for (int i = 0; i < 5; i++) {
            if (i == 2) {
                break;
            }
            System.out.println(i);
        }

        // final keyword
        final String name = "Alice";

        // null keyword
        String emptyString = null;

        System.out.println("Age: " + age);
        System.out.println("Initial: " + initial);
        System.out.println("Pi: " + pi);
        System.out.println("Discount: " + discount);
        System.out.println("Name: " + name);
        System.out.println("Empty String: " + emptyString); 
    }
}

Output
0
1
Age: 25
Initial: J
Pi: 3.14159
Discount: 0.1
Name: Alice
Empty String: null

Keywords in Python:

Below is the list of keywords in Python:

False, None, True, and, as, assert, async, await, break, class, continue, def, del, elif, else, except, finally, for, from, global, if, import, in, is, lambda, nonlocal, not, or, pass, raise, return, try, while, with, yield

Example:

Python
# def, for, if, in, return, continue keyword
def find_even_number(numbers):
  for number in numbers:
    if number % 2 == 0:
      return number
    else:
      continue
  return None 

# Example usage
numbers = [1, 3, 5, 4, 2, 8]
even_number = find_even_number(numbers)

if even_number is not None:
  print(f"First even number: {even_number}")
else:
  print("No even number found in the list.")

# True, False keyword
is_sunny = True
is_raining = False

# Pass keyword
if is_sunny:
  print("Let's go outside!")
else:
  pass  # Do nothing in this case (placeholder)

if is_raining:
  print("Bring an umbrella!")

Output
First even number: 4
Let's go outside!

Keywords in C#:

Below is the list of keywords in C#:

abstract, as, base, bool, break, byte, case, catch, char, checked, class, const, continue, decimal, default, delegate, do, double, else, enum, event, explicit, extern, false, finally, fixed, float, for, foreach, goto, if, implicit, in, int, interface, internal, is, lock, long, namespace, new, null, object, operator, out, override, params, private, protected, public, readonly, ref, return, sbyte, sealed, short, sizeof, stackalloc, static, string, struct, switch, this, throw, true, try, typeof, uint, ulong, unchecked, unsafe, ushort, using, virtual, void, volatile, while

Example:

C#
using System;

public class GFG {
    static public void Main()
    {
        // bool, int, char and float keyword
        bool isLoggedIn = true;
        int age = 30;
        char initial = 'A';
        float discount = 0.15f;
      
        // for, continue, break keyword
        for (int i = 0; i < 5; i++) {
            if (i == 2) {
                break; 
            }
            else if (i % 2 == 0) {
                continue; 
            }
            Console.WriteLine(i); 
        }

        Console.WriteLine("Is logged in: {0}", isLoggedIn);
        Console.WriteLine("Age: {0}", age);
        Console.WriteLine("Initial: {0}", initial);
        Console.WriteLine("Discount: {0:P}", discount);
    }
}

Output
1
Is logged in: True
Age: 30
Initial: A
Discount: 15.00 %

Keywords in JavaScript:

Below is the list of keywords in JavaScript:

break, case, catch, class, const, continue, debugger, default, delete, do, else, enum, export, extends, false, finally, for, function, if, import, in, instanceof, new, null, return, super, switch, this, throw, true, try, typeof, var, void, while, with, yield

Example:

JavaScript
// function keyword
function gradeCalculator(score) {
  if (score >= 90) {
    return "A";
  } else if (score >= 80) {
    return "B";
  } else if (score >= 70) {
    return "C";
  } else if (score >= 60) {
    return "D";
  } else {
    return "F";
  }
}

// const keyword
const myScore = 85;
const letterGrade = gradeCalculator(myScore);
console.log("Your grade is:", letterGrade);

// new keyword
const currentDate = new Date();
console.log("Today's date:", currentDate);

// Switch, case and default keyword
let day = 3;
switch (day) {
  case 0:
    console.log("Sunday");
    break;
  case 1:
    console.log("Monday");
    break;
  case 2:
    console.log("Tuesday");
  case 3:
    console.log("Wednesday");
    break;
  default:
    console.log("Invalid day number");
}

Output
Your grade is: B
Today's date: 2024-06-04T09:43:50.196Z
Wednesday

Keywords are the foundational elements of programming languages, defining the syntax and structure. They are reserved words with specific meanings, crucial for writing clear and effective code. Understanding and correctly using keywords is fundamental to mastering any programming language.



Contact Us