Javatpoint Logo
Javatpoint Logo

Counter variable in Java

A counter variable in Java is a special type of variable which is used in the loop to count the repetitions or to know about in which repetition we are in. In simple words, a counter variable is a variable that keeps track of the number of times a specific piece of code is executed.

The counter variable is declared and used in the same way as the normal variables are declared and used. The counter variable can be of only integer type because it is very easy to increase the value of integer type variable.

The counter variable is very easy to understand and use. The technique of using the counter variable in Java is as follows:

  1. Before the repeating cycle, we have to initialize it to zero or one.
  2. After that, we have to increase the counter variable in one within the respective cycle.

Let's take a simple example to understand the concept of the counter variable in Java.

CounterVariableExample1.java


Counter variable in Java

Let's take another example of a counter variable in which we will count the occurrence of the character in the string using counter variable.

CounterVariableExample2.java

Output

Counter variable in Java





Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA