aspose file tools
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Static Reference Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Reply Bookmark "Static Reference" Watch "Static Reference" New topic
Author

Static Reference

Alk
Greenhorn

Joined: Feb 02, 2000
Posts: 25
Consider the following piece of code, and select the statements which are true.

class Test{
int x = 5;
static String s = "abcd";

public static void method(){
System.out.println(s + x);
}
}

1)The code compiles and displays "abcd5".
2)The code compiles, but throws an exception at runtime, because variable x isn't declared as static.
3)The code fails to compile because you can't make a static reference to a non-static variable.
4)The code will compile and display "abcd5" if x is declared to be static.
5)The code will compile by removing the static keyword from the declaration of method().
The code will compile by removing the static keyword from the declaration of method().
I thoguht the answers are 3) and 4), but 5) is also given as correct answer.
Thandapani Saravanan
Ranch Hand

Joined: Oct 17, 1999
Posts: 117
3, 4 and 5 are correct answers. How 5?
Once the amethod becomes instance (by removing static keyword), it can use instance variables. Only static methods can not use them directly, because there is no instance associated with those methods.

Saravanan
paul wheaton
Trailboss

Joined: Dec 14, 1998
Posts: 19679
    ∞

I come up with 3, 4 and 5.
If method() is not static, it will have valid access to both x and s.

permaculture forums
 
I agree. Here's the link: http://zeroturnaround.com/jrebel - it saves me about five hours per week
 
subject: Static Reference
 
Similar Threads
Questions from Jxam
Sun Cirtification
this reference in static class
my notes on JLS for any1 who needs them !!
Jxam #47