60 337
Assignments Done
98%
Successfully Done
In April 2018

Answer to Question #59396 in Java | JSP | JSF for Peter

Question #59396
Person persons[] = new Person[5];

public static int femaleNum(Person[] persons){

int count = 0;

for(Person p : persons){
if (p.getGender() == 'F'){

count++;
}
}

Can you please explain what the meaning of "Person p : persons" inside the for loop is?
What is p and where does it come from? What is the meaning of ":"? Thanks.
Expert's answer
In a basics it looks like this - for(Type of iteration variable: collection) unit operators. In our example persons – it is collection of Person elements, in our case array. In this case creates a link “p”(type – Person), which in order assigned to each element of the array. You can rewrite this loop with the standart for loop realization:
// for each
int count = 0;
for(Person p : persons){
if (p.getGender() == 'F'){
count++;
}
// for loop
int count = 0;
for(int i = 0; i < persons.size(); i++){
if (persons[i] == 'F'){
count++;
}
You are asking what is p – it is a single instance of the collection – for Person[] it will be Person,
for int[] it will be int, for Object[] it will be Object.
‘:’ – it is a part of for each style – it means that it will iterate throw every element of the collection persons.

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be first!

Leave a comment

Ask Your question

Submit
Privacy policy Terms and Conditions