aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes variable this is undefined ? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "variable this is undefined ?" Watch "variable this is undefined ?" New topic
Author

variable this is undefined ?

Pankaja Shinde
Ranch Hand

Joined: Sep 15, 2006
Posts: 87
Consider the following class:

public class Test
{
public static void test()
{
this.print();
}
public static void print()
{
System.out.println("Test");
}
public static void main(String args [])
{
test();
}
}

What is the result of compiling and running this class?

A. The string Test is printed to the standard out.
B. A runtime exception is raised stating that an object has not been created.
C. Nothing is printed to the standard output.
D. An exception is raised stating that the method test cannot be found.
E. An exception is raised stating that the variable this can only be used within an instance.
F. The class fails to compile stating that the variable this is undefined.

Correct Answer : Option F

Why ?

Pankaj Shinde
Pandharinath Barve
Greenhorn

Joined: Aug 04, 2006
Posts: 13
you can not use "this" in static context.

Regards,
Pandharianth.


With Best Regards,<br />Pandharinath.<br />SCJP 5.0
anil kumar
Ranch Hand

Joined: Feb 23, 2007
Posts: 447
Hi

In static method there is no access to the keyword this or super.
Bijendra S. Rajput
Ranch Hand

Joined: Sep 19, 2006
Posts: 41
Hi Pankaja,

Yes, the ans of this question is F. This will fail at compile time.
The reason is that print() is a static method and when we are calling this method inside test() method, we are using this which is totally wrong. With static methods we can not use this keyword, static methods belongs to class. So this program will not compile.

if you can modify, like this

public static void test(){
print();

}


then this program will run and output will be "Test".


Thanks <br /> <br />Regards,<br />------------------------------<br />Bijendra S. Rajput<br />SCJP 1.5<br />------------------------------
 
Consider Paul's rocket mass heater.
 
subject: variable this is undefined ?