Win a copy of The Little Book of Impediments (e-book only) this week in the Agile and Other Processes forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

what is difference (for loop)

 
Nil. Hatamova
Greenhorn
Posts: 29
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi friends . I have two code. I dont know what is difference between them. The first one is a mock question from Mala Gupta book. I selected the answer is Java Java . But it is wrong.


Output :
OCA
Java


Then i change code like this for check answer is same or not. But it isn't same. Why?


Output:
Java
Java
 
Max Ma
Greenhorn
Posts: 13
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The first snipet assgin new eJava to c but didn't store the c back to the array.

The second snippet assign new eJava to c and replaced the old one in the array.
 
Max Ma
Greenhorn
Posts: 13
  • Likes 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
the first snippet is effectivley like this

for(int i = 0; i< course.lenth; i++){
EJava ej = course[i];
ej = new EJava()
}
 
Roel De Nijs
Sheriff
Posts: 10662
144
AngularJS Chrome Eclipse IDE Hibernate Java jQuery MySQL Database Spring Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Nil. Hatamova wrote:Then i change code like this for check answer is same or not. But it isn't same. Why?

Because there is a very important difference between both code snippets! Let's have a look at the relevant parts of both code snippets. Let's start with the first code snippetIn this for loop you are iterating through the array course using a seperate reference variable c to refer to the EJava object on each iteration. So at the first iteration, reference variable c is referring to the same object as course[0]. But then a newly created EJava object is assigned to reference variable c. But this only affects the value of reference variable c, not course[0] and therefore the value of course[0] remains unchanged (and it is still referring to the object created on line5 (which instance member courseName was changed on line6).

Now let's take a look at the second code snippetIn this for loop you are iterating through the array course using the array reference variable course and an index to refer to the EJava object on each iteration. If you assign a new EJava object to this reference variable (e.g. course[0]), it definitely affects this reference variable and this reference variable refers to another object (and thus the content of the array has been changed).

The first for loop is very similar to this code snippetAnd here is another alternative with the same outcome

Now let's see if you have understood all the above with a pop quiz question. What is the output of this code snippet?

Hope it helps!
Kind regards,
Roel
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic