Menu
Topics Index
...
`

GPREC Students


If you need explanation Read this topic

If you need Answer Take test on this topic

GPREC Students
What will be the output of the following program?
import java.util.*;
public class StudentRanks {
    public static void main(String[] args) {
        Set<Student> students = new TreeSet<Student>();
        students.add(new Student("sreeram", 5, 'C'));
        students.add(new Student("karthik", 1, 'A'));
        students.add(new Student("Ram", 1, 'B'));
        students.add(new Student("Yeshwanthi", 5, 'D'));
        students.add(new Student("bhavya", 2, 'E'));
        System.out.println(students);
    }
}
class Student implements Comparable<Student> {
    String name; int rollNumber; char section;
    public Student(String name, int rollNumber, char section) {
        this.name = name; this.rollNumber = rollNumber;
        this.section = section;
    }
    public int compareTo(Student o) {
        return name.substring(rollNumber).compareToIgnoreCase(o.name.substring(o.rollNumber));
    }
    public String toString() { return name; }
}

A. [bhavya, karthik, Ram, sreeram, Yeshwanthi]
B. [sreeram, Yeshwanthi, karthik, bhavya]
C. [Ram, Yeshwanthi, bhavya, karthik, sreeram]
D. Some other output
E. Compilation Error or Runtime Error
Topic: Java Comparators

If you need explanation Read this topic

If you need Answer Take test on this topic

User comments below. All of them might not be correct.

ans is B,here TreeSet makes the elments in sorted manner,here compareTo method comparing each element of set with substring of his name with rollNumber as index by last element in the soretd set .

Posted by Raviteja Daggupati    2014-05-02 09:11:52


Ans is E successfully compiles but exception occurs as string index is out of range:-1

Posted by Bharath Yelchuri    2014-05-02 09:13:00


No winner for this dose. Correct option is 'B' :(. Raviteja Daggupati was already won in this week.

Posted by Merit Campus    2014-05-05 04:37:41


© meritcampus 2019

All Rights Reserved.

Open In App