This week's book giveaways are in the Refactoring and Agile forums.
We're giving away four copies each of Re-engineering Legacy Software and Docker in Action and have the authors on-line!
See this thread and this one for details.
Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Strange question

 
Gitesh Ramchandani
Ranch Hand
Posts: 274
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 99
Eclipse IDE Mac
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Jesper de Jong
Java Cowboy
Saloon Keeper
Posts: 15207
36
Android IntelliJ IDE Java Scala Spring
 
raghu nagabandi
Ranch Hand
Posts: 35
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Interface variables are implecitly
public static final
 
Gitesh Ramchandani
Ranch Hand
Posts: 274
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thanks for help.

The source of question is unknown, i found it in some materials (txt file) i downloaded from net.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic