This week's book giveaway is in the Agile and other Processes forum.
We're giving away four copies of The Mikado Method and have Ola Ellnestam and Daniel Brolund on-line!
See this thread for details.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Strange question Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


Win a copy of The Mikado Method this week in the Agile and other Processes forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Reply Bookmark "Strange question " Watch "Strange question " New topic
Author

Strange question

Gitesh Ramchandani
Ranch Hand

Joined: Feb 28, 2007
Posts: 274
For the following code sample:

interface foo {
int k = 0;
}

public class test implements foo {
public static void main(String args[]) {
int i;
test t = new test();
i= t.k;
i= test.k;
i= foo.k;
}
}

What is the result?

A. Compilation succeeds.
B. An error at line 2 causes compilation to fail.
C. An error at line 9 causes compilation to fail.
D. An error at line 10 causes compilation to fail.
E. An error at line 11 causes compilation to fail.
Ans: A

Doubt: if I modify the code as
int i;
System.out.println(i);

test t = new test();
System.out.println(i);
i= t.k;

it gives compilation error �variable i might not have been initialized�.

Why is this so?

pls help
regards,
gitesh
Abdullah Mamun
Ranch Hand

Joined: Mar 19, 2007
Posts: 99

int i;
System.out.println(i);
...
it gives compilation error �variable i might not have been initialized�.

Why is this so?


You cannot use any local variable before initializing. But you can use instance variables without initializing because they are initialized by the default values.


MooN
Jesper de Jong
Java Cowboy
Bartender

Joined: Aug 16, 2005
Posts: 12928
    
    3

Note: Please quote your sources


Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 7 API documentation
Scala Notes - My blog about Scala
raghu nagabandi
Ranch Hand

Joined: Aug 14, 2007
Posts: 35
Interface variables are implecitly
public static final
Gitesh Ramchandani
Ranch Hand

Joined: Feb 28, 2007
Posts: 274
thanks for help.

The source of question is unknown, i found it in some materials (txt file) i downloaded from net.
 
I agree. Here's the link: http://ej-technologies/jprofiler - if it wasn't for jprofiler, we would need to run our stuff on 16 servers instead of 3.
 
subject: Strange question
 
Similar Threads
Question about class and interface
Interface qustion
getInt()
Instance Members' values
two possible answers Q18 ch 4 page 282 from KB