In: Computer Science
Write a for-each loop that prints all of the Student objects in an ArrayList<student> object called roster. Write this piece in Java.
Write the correct code to execute.
Code in java:
//for-each loop that prints all of the Student objects
in an
//ArrayList<student> object called roster.
import java.util.*;
//defining class student
class Student{
String name;
Student(String name){
this.name=name;
}
@Override
public String toString() {
return ("Student object Names:"+this.name); //prints student
names
}
}
class Main{
public static void main(String args[]){
//Creating user-defined class objects
Student s1=new Student("charith");
Student s2=new Student("srikar");
Student s3=new Student("sai");
//creating arraylist
ArrayList<Student> roaster =new
ArrayList<Student>();
roaster.add(s1);//adding Student class
object
roaster.add(s2);
roaster.add(s3);
//for each loop :it iterates through each student object in
roaster
//and calls respective toString method
roaster.forEach((n) ->System.out.println(n));
}
}
Screenshot code:
Output: