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;
}
Outputnum = 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;
}
OutputYou 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);
}
}
Output0
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!")
OutputFirst 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);
}
}
Output1
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");
}
OutputYour 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.
Similar Reads
What is a Code in Programming?
In programming, "code" refers to a set of instructions or commands written in a programming language that a computer can understand and execute. In this article, we will learn about the basics of Code, types of Codes and difference between Code, Program, Script, etc. Table of Content What is Code?Co
10 min read
What are Operators in Programming?
Operators in programming are essential symbols that perform operations on variables and values, enabling tasks like arithmetic calculations, logical comparisons, and bitwise manipulations. In this article, we will learn about the basics of operators and their types. Operators in Programming Table of
15+ min read
What is a Block in Programming?
In programming, a block is a set of statements that are grouped and treated as a single unit. Blocks are used to define the scope of variables, control the flow of execution in conditional statements and loops, and encapsulate code in functions, methods, or classes. Table of Content What is a Block
6 min read
What is Imperative Programming?
The computer programming paradigm defines the style of programming, approach to solve problem and method of computer systems towards providing solutions use programming. There is a classification of programming paradigms into two broad paradigms i.e., imperative and declarative. This article is base
6 min read
What are Objects in Programming?
In object-oriented programming (OOP), objects are the basic entities that actually exists in the memory. Each object is based on a blueprint of attributes and behaviours (variables and functions) defined as Class. The basic purpose of a Class is to identify the common attributes and behaviours and g
2 min read
What are Identifiers in Programming?
Identifiers are names given to various programming elements, such as variables, functions, classes, constants, and labels. They serve as labels or handles that programmers assign to program elements, enabling them to refer to these elements and manipulate them within the code. In this article, we wi
3 min read
What is Programming? A Handbook for Beginners
Diving into the world of coding might seem intimidating initially, but it is a very rewarding journey that allows an individual to solve problems creatively and potentially develop software. Whether you are interested out of sheer curiosity, for a future career, or a school project, we are here to a
13 min read
Loops in Programming
Loops or Iteration Statements in Programming are helpful when we need a specific task in repetition. They're essential as they reduce hours of work to seconds. In this article, we will explore the basics of loops, with the different types and best practices. Loops in ProgrammingTable of Content What
12 min read
Assignment Operators in Programming
Assignment operators in programming are symbols used to assign values to variables. They offer shorthand notations for performing arithmetic operations and updating variable values in a single step. These operators are fundamental in most programming languages and help streamline code while improvin
7 min read
Introduction to GUI Programming in C++
In C++, Graphical User Interface (GUI) programming is important in modern application development where users have nice graphics for them to work with. Although C++ is commonly linked with system programming and game writing, it can be an excellent alternative to GUI writing. In this article, we wil
5 min read