1

I am new to java, and I need help understanding what the code is trying to do. I am interested on the last line( sd.setId(sh.getGrade().getSchoolId());). I know it is setting using setId in sd object, but then I am bit confused what the rest of the line(sh.getGrade().getSchoolId()) is trying to do. Does getSchoolId() method called first and then sh.getGrade() and set everything in sd? How do I read a code when there are multiple dot(.) operators in a single line of code?

while (oneIter.hasNext()) {
 ShoolHistory sh= (ShoolHistory) oneIter.next();
 ScoolDetailId sd = new ScoolDetailId();
 sd.setId(sh.getGrade().getSchoolId());
pj_max
  • 127
  • 8
  • Left to right. It gets the grade from the school history, then the school ID from the grade, then sets that to the detail ID. – daniu Jun 09 '21 at 05:45

3 Answers3

5

For something like this it would be easiest to just split each command open into several lines. Then your result will be:

while (oneIter.hasNext()) {
    ShoolHistory sh = (ShoolHistory) oneIter.next();
    ScoolDetailId sd = new ScoolDetailId();
    Grade grade = sh.getGrade(); // I'm just assuming some types here and for the id
    Integer id = grade.getSchoolId(); // I like btw the usage of all possible variations of writing "school"
    sd.setId(id);
}

So, if you have a line with multiple dot-operators, you start just reading left to right as you would normally do. Then, if it is like here used as arguments for some methods, you go from inside to outside.

Christian
  • 1,437
  • 2
  • 8
  • 14
  • Awesome, I see it. so it is few lines of code chained together. Thank you, Christian . I always get confused every time I see method chaining together. – pj_max Jun 09 '21 at 06:02
4

I'm assuming that sh.getGrade() returns an object of the type Grade which is defined outside the scope of this code. And then a method called getSchoolId() is called on that object which returns the ID which is then passed to the sd.setId method.

So it is equivalent to this:

Grade grade = sh.getGrade();
String id = grade.getSchoolId();
sd.setId(id);

You're just skipping the extra variables by chaining the methods together,

geanakuch
  • 778
  • 7
  • 13
  • 24
3

As you might be already aware that Java is Object oriented programming. Hence mostly you would be dealing with objects.

Always remember to read from left to right. So in your case you are trying to set the 'id' field in 'schoolDetailsId' object.

The 'id' field is obtained from another object which is in 'grade' object which is inside 'SchoolHistory (sh)'

SchoolHistory --> grade --> schoolId

You could refer this link to understand more.

Vikas Adyar
  • 149
  • 1
  • 8