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 this operator 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 "this operator" Watch "this operator" New topic

this operator

Gagan Deep
Ranch Hand

Joined: Aug 23, 2005
Posts: 47
Q43.What will be the result of compiling and running the given program?
Select one correct answer.

1. class Q43
2. {
3. int y=1;
4. Q43()
5. {
6. this(y);
7. }
8. Q43(int x)
9. {
10. y=x++ + ++x;
11. }
12. public static void main(String [] args)
13. {
14. Q43 t = new Q43();
15. System.out.println(t.y);
16. }
17. }
1. Program compiles correctly and prints 1 when executed.
2. Program compiles correctly and prints 4 when executed.
3. Compile time error.
4. None of above.

Answer is 3.

Can some once help me in understanding this?
Mike Noel
Ranch Hand

Joined: Dec 15, 2005
Posts: 108
I don't understand the error either. I think that it has to do with constructor chaining and that's something that I only have a basic grasp on. I did a search in the forums and found some discussion about this here:

The compilation error is

If you search for this in the forum search you'll find another dozen or so topics that discuss it.


Mike Noel
A Kumar
Ranch Hand

Joined: Jul 04, 2004
Posts: 980
you cannot use instance variables for constructor chaining

You can use static variables.
santosh kothapalli

Joined: Dec 27, 2005
Posts: 26
The simplest of answers is you cannot use the instance variables in construstors to expressions or calculations ,but only to initialize else the compiler throws an error.
Just to make it official, you can find the rule in the JLS

Santosh K<br />SCJP 1.4,SCWCD
Gagan Deep
Ranch Hand

Joined: Aug 23, 2005
Posts: 47
Thanks to all for replying.

i found the following from the link suggested by santosh

An explicit constructor invocation statement in a constructor body may not refer to any instance variables or instance methods declared in this class or any superclass, or use this or super in any expression; otherwise, a compile-time error occurs.

I agree. Here's the link:
subject: this operator
It's not a secret anymore!