wood burning stoves 2.0*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Doubt........ Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of The Java EE 7 Tutorial Volume 1 or Volume 2 this week in the Java EE forum
or jQuery UI in Action in the JavaScript forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Doubt........" Watch "Doubt........" New topic
Author

Doubt........

Vishakha Ahuja
Ranch Hand

Joined: Sep 13, 2000
Posts: 191
Given the following method and definition and assuming that Str array is correctly initialized and filled elsewhere :
1. String [] Str ;
2. public int findstring(String find) {
3. for ( int i = 0; i < Str.length ; i++){
4. if ( find.equalsIgnoreCase( Str[i] )) return i ;
5. }
6. System.out.println("Last String Examined : " + Str[i-1]);
7. return -1;
8. }
What will happen when we compile this code and use this method to look up a String which does not occur in Str array ?
a. NullPointerException will be generated at line 6.
b. The compiler will object to line 6.
c. The last String in the array will be written to standard output by line 6.
d. "Last String Examined : null" will be written to standard output by line 6.
The correct answer given is b...........HOW..........???
Please explain the answer.
Amit Punjwani
Ranch Hand

Joined: Jul 10, 2000
Posts: 50
Hi Vishaka,
The correct ans is b)The compiler will object at line 6.
It's simple. At line 6 u r trying to access variable i which is local to the block i.e for loop . U cannot access the variable i outside the loop.
Try to declarean initialize the var i before the loop probably u would get the ans d) "Last String Examined : null" will be written to standard output by line 6.
Hope u got it
Good Luck
Michal Harezlak
Ranch Hand

Joined: Jul 06, 2000
Posts: 185
Variable i is undefined in line 6. The definition in the loop applies only to the loop's scope.
Vishakha Ahuja
Ranch Hand

Joined: Sep 13, 2000
Posts: 191
Thanks Amit.
I suppose as my exam is coming nearer, I'm getting a little tensed up. I was only thinking about the scope of Str and not of variable i. Hmm, guess I've to be more careful. With only one day remaining for my exam, I'm making such silly mistakes......
Vishakha Ahuja
Ranch Hand

Joined: Sep 13, 2000
Posts: 191
Thanks Michal.
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Doubt........