I saw the following code on a website but do not know what does this do, when I use it it shows an error.
for(String next: var)
I saw the following code on a website but do not know what does this do, when I use it it shows an error.
for(String next: var)
Its java for each loop
. where var is a reference which implements iterable
An enhanced for loop for the Java™ Programming Language
see:http://docs.oracle.com/javase/1.5.0/docs/guide/language/foreach.html
its called for each loop in Java
for it to work, var
should be of type String[]
OR Collection<String>
which is essentially Iterable<String>
its equivalent of
for(int i=0; i < var.length; i++) {
String next = var[i];
}
in case of var
is String[]
and
for (Iterator<String> itr = var.iterator(); itr.hasNext();)
{
String next = itr.next();
}
in case where var
is Collection<String>
It's like writing:
for (Iterator<String> itr = var.iterator(); itr.hasNext();)
{
String str = itr.next();
...
}
See this link for details.
it will iterate loop till your next variable has values. you can access that value using next variable
a very interesting question for beginners, this is a foreach loop similar to for loop, it will assign each value of var which is any array of type String to next.
for more information refer this for each loop
var
must be List of String
Objects ,
for(Object s:List){}
is a For each loop
or enhanced for each loop.
It is easy to iterate like this , rather than using
List<String> var=new ArrayList<String>();
for(int i=0;i<var.length();i++)
{
String s=var.get(i); //var is a list of String
System.out.println(s);
}
For each is used this way
for(String s:var)
{
System.out.println(s); //much easy
}
So to ease up Java allows for each loop to iterate through List through for each.