File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
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

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()
public static void print()
public static void main(String args [])

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

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


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

Joined: Feb 23, 2007
Posts: 447

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(){


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

Thanks <br /> <br />Regards,<br />------------------------------<br />Bijendra S. Rajput<br />SCJP 1.5<br />------------------------------
I agree. Here's the link:
subject: variable this is undefined ?
It's not a secret anymore!