• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Doubt........

 
Vishakha Ahuja
Ranch Hand
Posts: 191
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 50
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 185
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Variable i is undefined in line 6. The definition in the loop applies only to the loop's scope.
 
Vishakha Ahuja
Ranch Hand
Posts: 191
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 191
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Michal.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic