Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

this operator

 
Gagan Deep
Ranch Hand
Posts: 47
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 108
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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:

http://www.coderanch.com/t/244427/java-programmer-SCJP/certification/When-does-become-availible

The compilation error is


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

_M_
 
A Kumar
Ranch Hand
Posts: 980
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
you cannot use instance variables for constructor chaining

You can use static variables.
 
santosh kothapalli
Greenhorn
Posts: 26
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
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 8.8.5.1
 
Gagan Deep
Ranch Hand
Posts: 47
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.

Thanks
Gagan.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic