Newbie Q. Accessing a variable in one method from another.

M

Mike Barnard

Hi again all.

Another very basic question from a TOTAL newbie. (I have a book and
I'm getting dangerous to myself now.) However unnecesary some of the
methods below are, I'm doing this to try to learn how to pass
information around.

Q: How does one refer to a variable which was declared in a different
method? My logic was to declare it in the class level block but that
brought the error message:

"G:\java\Projects>javac starnumbers.java
starnumbers.java:28: non-static variable numberStore cannot be
referenced from a
static context
numberStore = new int[number] ;
^
1 error"

I know there's lots of lessons for me to learn yet, but as I only get
about an hour an evening if I'm lucky, it may take some time! This
seems to be the point where I need to learn about static and non
static.











/*
Self tutorial.
Get a user to enter 10 numbers.
display the correct number of stars for each number.
Store the numbers in an array.
Print them all in one go.
*/

public class starnumbers
{
int[] numberStore; // A place to store all of the numbers.
//This was originally in main with 'number'.

public static void main (String[] args)
{
int iterations = 10 ; // number of times to loop.
int number = 0;

initialise (iterations) ;
displayInstructions ();
getAKeypress();
//validateNumber();
//displayStars();
}

public static void initialise (int number)
{
numberStore = new int[number] ;
}

public static void displayInstructions ( )
{
System.out.println("V 1.01 - Instructions");
System.out.println("Use the keyboard to enter single numbers");
System.out.println("You need to enter 10 numbers.\n\n");
System.out.print("Start now...");
}

public static void getAKeypress ()
{
//next bit to study...
}
}
 
M

markspace

Mike said:
"G:\java\Projects>javac starnumbers.java
starnumbers.java:28: non-static variable numberStore cannot be
referenced from a
static context
numberStore = new int[number] ;
public class starnumbers
{
int[] numberStore; // A place to store all of the numbers.

static int[] numberStore;
//This was originally in main with 'number'.

public static void main (String[] args)
{

This is an easy one. Just make the change that I added above and you're
good to go.

To try to explain this a bit more, static on a method means that the
method isn't attached to any one instance of the class, it's attached to
the class itself. Same for variables. Static means they're attached to
the class (sort like a "global" variable) and not static means the
variable is attached to an instance.

The problem with what you had was a static method was trying to access a
non-static (instance) variable. And you don't have an instance in that
case. So, it fails.

The other thing you could have done, is not make the change I gave you,
then do something like this:

public static void main( String... args ) {
starnumbers sn = new starnumbers();
int number = 5;
sn.numberStore = new int[number];
// ...

See? Now I have an instance, referred to as "sn", so I can use the
instance variable called numberStore with it.

Hope that made sense.

(P.S., also, please use proper capitalization of your class names, e.g.
"StarNumbers".)
 
L

Lew

Mike said:
"G:\java\Projects>javac starnumbers.java
starnumbers.java:28: non-static variable numberStore cannot be
referenced from a
static context
numberStore = new int[number] ;

public class starnumbers {
int[] numberStore; // A place to store all of the numbers.

static int[] numberStore;

//This was originally in main with 'number'.

public static void main (String[] args)
{
This is an easy one. Just make the change that I added above and you're
good to go.

To try to explain this a bit more, static on a method means that the
method isn't attached to any one instance of the class, it's attached to
the class itself. Same for variables. Static means they're attached to
the class (sort like a "global" variable) and not static means the
variable is attached to an instance.

The problem with what you had was a static method was trying to access a
non-static (instance) variable. And you don't have an instance in that
case. So, it fails.

The other thing you could have done, is not make the change I gave you,
then do something like this:

public static void main( String... args ) {
starnumbers sn = new starnumbers();
int number = 5;
sn.numberStore = new int[number];
// ...

See? Now I have an instance, referred to as "sn", so I can use the
instance variable called numberStore with it.

Hope that made sense.

(P.S., also, please use proper capitalization of your class names, e.g.
"StarNumbers".)

There are three basic kinds of variables - static, instance and local.

Static variables belong to the class itself.

Instance variables belong to an instance, or object, of the class.

Local variables are restricted to a block (code between curly braces).

Static methods cannot refer to instance variables.

Code outside a block cannot refer to variables local to that block.

Then there's the matter of 'public', 'protected', package-private and 'private'.

public class FooBar
{
static String belongaType = "This is attached to the class itself";

String belongaInstance = "This is attached to a particular instance";

public static void doSomething()
{
String belongaMethod = "This method cannot use 'belongaInstance'";
System.out.println( belongaType );
// System.out.println( belongaInstance ); // would cause compiler error
System.out.println( belongaMethod );
if ( belongaBlock != null )
{
String belongaBlock = "This is local to the 'if' block";
System.out.println( belongaBlock );
}
// System.out.println( belongaBlock ); // would cause compiler error
}

public void instanceLevel()
{
String belongaLocal = "This method cannot use 'belongaInstance'";
System.out.println( belongaType );
System.out.println( belongaInstance ); // no compiler error
System.out.println( belongaLocal );
if ( belongaBlock != null )
{
String belongaBlock = "This is not the same 'belongaBlock'";
System.out.println( belongaBlock );
}
// System.out.println( belongaBlock ); // would cause compiler error
}

public static void main( String [] args )
{
doSomething();
new FooBar().instanceLevel();
}
}

For a fast introduction to all this, since you have limited time:
<http://java.sun.com/docs/books/tutorial/java/nutsandbolts/index.html>
 
M

Mike Barnard

Good morning Mark, and thanks.
Mike Barnard wrote:
public class starnumbers
{
int[] numberStore; // A place to store all of the numbers.

static int[] numberStore;
This is an easy one. Just make the change that I added above and you're
good to go.

I knew static was relevant but had no concept of what it meant. But
Now I know, I think. See reply to other message below.
To try to explain this a bit more, static on a method means that the
method isn't attached to any one instance of the class, it's attached to
the class itself. Same for variables. Static means they're attached to
the class (sort like a "global" variable) and not static means the
variable is attached to an instance.

And as I had / have no instance as such... kablooey.
The problem with what you had was a static method was trying to access a
non-static (instance) variable. And you don't have an instance in that
case. So, it fails.

Heh, wot I said.
The other thing you could have done, is not make the change I gave you,
then do something like this:

public static void main( String... args ) {
starnumbers sn = new starnumbers();
int number = 5;
sn.numberStore = new int[number];
// ...

See? Now I have an instance, referred to as "sn", so I can use the
instance variable called numberStore with it.
Hope that made sense.

(P.S., also, please use proper capitalization of your class names, e.g.
"StarNumbers".)

OK, refreshed on that too.

Thanks for taking the time to reply in a way a tiny brain like mine
can understand! :)

Mike.
 
M

Mike Barnard

Good morning Lew.
Mike Barnard wrote:
There are three basic kinds of variables - static, instance and local.

Static variables belong to the class itself.

Instance variables belong to an instance, or object, of the class.

Local variables are restricted to a block (code between curly braces).

Static methods cannot refer to instance variables.

Code outside a block cannot refer to variables local to that block.

Then there's the matter of 'public', 'protected', package-private and 'private'.

Snip cool example.
For a fast introduction to all this, since you have limited time:
<http://java.sun.com/docs/books/tutorial/java/nutsandbolts/index.html>

The link is a perfect answer to my question. The phrase "...this tells
the compiler that there is exactly one copy of this variable in
existence, regardless of how many times the class has been
instantiated. " summed it up for me. Static. OK, getting there. Public
etc next.

But this makes me ask a question, that I'll experiment with tonight I
hope.

Q. If I declare such a class-level static variable *within a method*,
bearing in mind the Sun tutorial statement that "...local variables
are only visible to the methods in which they are declared; they are
not accessible from the rest of the class." will that limit what other
code can access the static variable? Will I only be able to see it
from inside the method? Which also makes me ask:

Q. What is the convention for creating such a variable? Place it in
the class, outside methods?

As I said, I'll experiment. And read more!

Thank you.

Mike.
 
L

Lew

Mike said:
Q. If I declare such a class-level static variable *within a method*,

You can't.
bearing in mind the Sun tutorial statement that "...local variables
are only visible to the methods in which they are declared; they are
not accessible from the rest of the class." will that limit what other
code can access the static variable? Will I only be able to see it
from inside the method? Which also makes me ask:

There is no such thing as a static variable declared within a method.
Q. What is the convention for creating such a variable? Place it in
the class, outside methods?

You can't.

Variables declared within a method are local, never static or instance.
 
M

Mike Barnard

On Wed, 23 Jun 2010 09:17:10 +0100, Mike Barnard

To both Lew and Wayne, thanks for the replies. Hopefully I'll get more
time tonight and play. I'll put a static variable in a method and see
what the error is, etc.
 
L

Lew

Lew said:
    public void instanceLevel()
    {
       String belongaLocal = "This method cannot use 'belongaInstance'";

That String lies. It should have been:

String belongaLocal = "This method *can* use 'belongaInstance'";

Sorry.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,581
Members
45,057
Latest member
KetoBeezACVGummies

Latest Threads

Top