• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Tim Cooke
  • Liutauras Vilda
  • Jeanne Boyarsky
  • paul wheaton
Sheriffs:
  • Ron McLeod
  • Devaka Cooray
  • Henry Wong
Saloon Keepers:
  • Tim Holloway
  • Stephan van Hulst
  • Carey Brown
  • Tim Moores
  • Mikalai Zaikin
Bartenders:
  • Frits Walraven

Question from mock exam: Sierra/Bates book, ch. 3

 
Ranch Hand
Posts: 86
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,
I'm having a real problem with these questions. Specifically question 9 in Chapter 3 of the Kathy Sierra/Bert Bates self test at the end. Here's the code:
public class Knowing {
static final long tooth = 343l;
static long doIt(long tooth) {
System.out.print(++tooth + " ");
return ++tooth;
}
public static void main(String[] args) {
System.out.print(tooth +" ");
final long tooth = 340l;
new Knowing().doIt(tooth);
System.out.println(tooth);
}
}
"What is the result?
a. 343 340 340
b. 343 340 342
c. 343 341 342
d. 343 341 340
e. 343 341 343
f. Compilation fails.
g. An exception is thrown at runtime."

I thought it was e, but I don't understand why it's D. I understand that the tooth within the main block is a local variable, but I guess I just need additional explanation as to why. Is there a hierarchy of which variables are chosen that I missed? Thanks.
 
Sheriff
Posts: 11343
Mac Safari Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
In this code, there are 3 variables called "tooth." One is a static variable whose scope is the entire class. Another is local to the doIt method, and the third is local to the main method.

When the first print statement executes in main, the local "tooth" has not been declared yet, so the class variable is used and 343 is printed. Then main's local variable "tooth" is declared with a value of 340. This is passed as an argument to the doIt method, where it is assigned to the "tooth" variable local to doIt. Inside that method, the local variable is incremented to 341 and printed. It is then incremented to 342 and returned. However, nothing is done with that returned value. Instead, the next line in main prints the value of "tooth," which now refers to the local variable declared 2 lines above that, which still has its value of 340.
 
Oh. Hi guys! Look at this tiny ad:
Gift giving made easy with the permaculture playing cards
https://coderanch.com/t/777758/Gift-giving-easy-permaculture-playing
reply
    Bookmark Topic Watch Topic
  • New Topic