Imperative programming is a programming paradigm that focuses on describing how a program should operate by specifying a sequence of actions to be performed. In imperative programming, a program consists of a series of statements that change the state of the program by modifying variables or data structures.
Here is a simple example of imperative programming in Java:
// Declare an integer variable and initialize it to 0 int count = 0; // Loop through a range of numbers for (int i = 0; i < 10; i++) { // Increment the count by 1 count++; } // Print the final value of count System.out.println(count); // Outputs: 10
This example uses a loop and a variable assignment to increment the value of count
by 1 ten times. The sequence of actions performed in this program are specified explicitly, and the program's state is changed as a result of these actions.
Other examples of imperative programming in Java include using loops to iterate over collections, using variables to store and manipulate data, and using statements like if
, switch
, and break
to control the flow of the program.