The explanation for lines line 1 and line 2 is as follows
now we are looping till the while condition returns true
the add method in set returns true if the element is added to the set
the set contains only the unique elements and not duplicate ones
in our example
we add "boo" twice
first time the array index 0 refers to the boo String but when we add it again then the array index 3 refers to it
the loop execution is as follows
for the first element
i.e. new String("boo");
the add method returns true as there is no duplicate element and loop executes
for the second element
i.e. new String("who")
same operation happens
now for the "are" again same thing happens
and now again we are adding new String("boo")
now this object already exists in set and duplicates are not allowed and the add method returns false
and hence the loop terminates and we do not get infinite loop
here is the output
nonce 0 who nonce 1 are nonce 2 boo
SCJP 6 [86%], OCPWCD [84%], OCEJPAD [83%]
If you find any post useful, click the "plus one" sign on the right
Set : Duplicates are not allowed
String : Overrides equals() .
boo who and are are successfully added after which loop condition becomes false.
I am just a bit confused about ; (Semicolon) after main method().
If it is allowed then output should be nonce nonce nonce
Complie time error!!!
SCJP 6.0 96%
(Connecting the Dots ....)
Joined: Apr 03, 2008
yeah, the extra semi-colons were added to make the code look odd and
thus a temptation to choose compile error, but they have no effect at all (at least in this example).
the key to a correct evaluation of the output is to consider the difference between:
in the both cases indx++ is computed but only in the second is the value of indx
(before the addition) printed.
a rule with printf seems (please correct is your experience is different) to be that while
there must be a matching arg for each conversion there is no requirement that each arg be
matched with a conversion.
if the arg or its result is to be output then there must be a matching conversion.
see also Question 12 for another trick with printf.
Joined: Apr 03, 2008
in order to see better what rules the compiler is using when adding to a set consider
the question as originally posted and add the following code right
after the while loop; what is the output ?