• Post Reply Bookmark Topic Watch Topic
  • New Topic

Is object created in a static method good for only that method.  RSS feed

 
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


This code gives error in the line 14 that it cannon find symbol ex while both the methods are static.
But works for this code

Please help..
 
Bartender
Posts: 4181
22
IntelliJ IDE Java Python
  • Likes 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Saba Shahrukh wrote:Is object created in a static method good for only that method.

A variable (the variable, not the Object it points to) only exists for the length of the block it was created in. So in the first example, the variable ex is created in the main method, and becomes unavailable at the closing bracket for the method. In the second example you create two different objects with two different references and each only exists in their own block.

Note this isn't specific for static methods, it is true for instance methods and for any other block. For example:

This wouldn't work because variable output is declared in the for loop, which is a block of code, and the block comes to an end before I try to print it.

 
Saba Shahrukh
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Steve..
Understood
 
lowercase baba
Bartender
Posts: 12565
49
Chrome Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Note that there is a difference between the REFERENCE created and the OBJECT created. If you create an object inside a static method and your code keeps a reference to it (maybe by adding it to a collection), then the object is still available.
 
Don't get me started about those stupid light bulbs.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!