File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Interface question......... Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Interface question........." Watch "Interface question........." New topic
Author

Interface question.........

sonir shah
Ranch Hand

Joined: Nov 01, 2001
Posts: 435
Consider the following code:

What will be the output when class Test is run ?
Options :1) It will print 1
2)It will print ii=2, j=3, jj=4 and then 1
3)It will print ii=2 and then 1
4)It will not compile
5)None of the above..
Answer: 1)It will print 1.
I cannot understand how does the output only prints 1 without printing the value of ii
??
Please explain..
Sonir
Maulin Vasavada
Ranch Hand

Joined: Nov 04, 2001
Posts: 1871
hi sonir,
very interesting thing happens here i guess.
try to print J.jj or I.ii. it prints the message in the out() method.
but again, its little strange. 'coz it also prints message for var 'j' in J interface when we just print J.jj!!
So, i guessed that all the vars initialized with const are compile time loaded and rest who depends upon some class thing gets loaded first time when ANY of the var is loaded (when we try to access it first time).
this loading is only ONCE as the vars are final. so, if u try to print J.jj again it just prints value of J.jj without calling out() method again.

here is the code i used,

the output was,
1
j 3
jj 4
4
4

any other pointers?
regards
maulin.
Rob Ross
Bartender

Joined: Jan 07, 2002
Posts: 2205
Yup Maulin, you are on the right track.
The expression J.i is a compile time constant. That is, the compiler can completely evaluate the value of J.i without having to load any classes/interfaces or run any code. That's because interface J inherits the i member from interface i, and the member i is a public, static, and final variable with a value 1. Since this value can never change while the program is running, the compiler is able to create code for the println() statement that just sticks the value "1" in-line, without having to look at the J interface at run time.

Rob


Rob
SCJP 1.4
sonir shah
Ranch Hand

Joined: Nov 01, 2001
Posts: 435
Hey guys..
I am still not clear with the concept..
Why does J.jj prints 2 sets of different answers??

 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Interface question.........