aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Using this to reference static variables Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Using this to reference static variables" Watch "Using this to reference static variables" New topic
Author

Using this to reference static variables

Ricardo Cortes
Ranch Hand

Joined: Jan 23, 2002
Posts: 140
I got this problem from one of the mock exams. Is it ok to access static members using the this reference?
---
Q. 17
What is the result of compiling and running the following code:

public class Test {
static int total = 10;
public static void main (String args []) {
new Test();
}
public Test () {
System.out.println("In test");
System.out.println(this);
int temp = this.total;
if (temp > 5) {
System.out.println(temp);
}
}
}

A. The class will not compile
B. The compiler reports and error at line 2
C. The compiler reports an error at line 9
D. The value 10 is one of the elements printed to the standard output
E. The class compiles but generates a runtime error
Answer is D.


Sun Certified J2EE Architect for the J2EE Platform (Part 1)<br />Sun Certified Web Component Developer for the J2EE Platform<br />Sun Certified Programmer for the Java 2 Platform
Roy Ben Ami
Ranch Hand

Joined: Jan 13, 2002
Posts: 732
yes its fine.
static variables can be accesed using the name of the class or using one of the instances created from the class. this refers to an instance so it doesnt make a problem.
but static methods cant access non static variables.
Raghav Sam
Ranch Hand

Joined: Apr 12, 2001
Posts: 412
Originally posted by Roy Ben Ami:

but static methods cant access non static variables.

yes, so, u cant have something like System.out.println(this.total); inside your main method.
HTH
Raghav
[ January 23, 2002: Message edited by: Raghav Sam ]

Be who you are and say what you feel, because those who mind don't matter and those who matter don't mind.<br />- Dr. Seuss
Ricardo Cortes
Ranch Hand

Joined: Jan 23, 2002
Posts: 140
Thank You!
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Using this to reference static variables