Learnerslesson
   JAVA   
  SPRING  
  SPRINGBOOT  
 HIBERNATE 
  HADOOP  
   HIVE   
   ALGORITHMS   
   PYTHON   
   GO   
   KOTLIN   
   C#   
   RUBY   
   C++   




Java - Iterating String


There are several ways using which we can iterate a String.


We will be looking at two different ways using which we can iterate the elements in a String.

  1. Iterate a String using for loop


  2. Iterate a String using for each loop


Iterate a String using for loop


Example :



public class MyApplication
{
    public static void main(String[] args)
    {
       	String x = "Hello";
        for (int i = 0; i < x.length(); i++) {
            System.out.println(x.charAt(i));
        }
    }
}


Output :



  H
  e
  l
  l
  o

In the above example, we have initialised the String type variable x with the String Hello.


String x = "Hello";

Then we have run the for loop


for (int i = 0; i < x.length(); i++) {
	System.out.println(x.charAt(i));
}

And in each Iteration of for loop, we have taken the help of charAt() method provided by String.


System.out.println(x.charAt(i));

So, in each Iteration, charAt(i) takes each letter from the String and prints it.


Next, let us see that how can we iterate a String using for each loop.


Iterate a String using for each loop


Example :



public class MyApplication
{
    public static void main(String[] args)
    {
       	String x = "Hello";
        for (char c : x.toCharArray()) {
            System.out.println(c);
        }
    }
}


Output :



  H
  e
  l
  l
  o

So, in the above example, we have initialised the value of x with Hello.


String x = "Hello";

Then we have used the for loop to iterate through each elements of the String.


for (char c : x.toCharArray())

To do that we have converted the String x to a char array,


x.toCharArray()
Spring_Boot


And in each Iteration, we are going to get the values of the String x and get in the local char type variable c.


And printed the value of every letters of the String x in each iteration.


System.out.println(c);