File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes Difference between declaring variables. Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Difference between declaring variables." Watch "Difference between declaring variables." New topic

Difference between declaring variables.

Joy Vergis
Ranch Hand

Joined: Sep 14, 2009
Posts: 48
Please let me know waht is the difference between declaring variables at line no.1 and line no. 2

I thought declaring a variables in the constructor Employee constructor will make the variable for the method getName(). but the same did not happen.

I am a bit confused with instance variable concept. Instance variable are accessible through the object of the class. So I declared it in the constructor itself. Now tha same variable is not accessible outside the constructor in the same class to other methods.

Please help to understand it.

John Jai

Joined: May 31, 2011
Posts: 1776
The variable @ line #12 are local variables visible only to the constructor block. Instance variables should be declared outside any method / block in the class. So try declaring the variables @ line #5.
Campbell Ritchie

Joined: Oct 13, 2005
Posts: 46332
. . . and why are you suppressing a deprecation warning? That looks suspicious to me.
Unnar Björnsson
Ranch Hand

Joined: Apr 30, 2005
Posts: 164
The constructor in no different than any other method or code block in terms of scope, variables declared inside a constructor or any other codeblock are not visible outside it. You should move the declaration of name outside the constructor while still giving it value of 'n' inside it.
Ted Smyth
Ranch Hand

Joined: May 28, 2008
Posts: 73
Campbell Ritchie wrote: . . . and why are you suppressing a deprecation warning? That looks suspicious to me.

Likewise. The getMonth() method of java.util.Date was deprecated some time ago (JDK 1.1, lol, that's some serious backwards compatibility right there).

Edward Smith
I agree. Here's the link:
subject: Difference between declaring variables.
It's not a secret anymore!