a question about java local variable

how to access local variable in the other method

Page 1 of 1

2 Replies - 3001 Views - Last Post: 13 April 2009 - 04:21 PM Rate Topic: -----

#1 Novice.Chimp   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 1
  • Joined: 13-April 09

a question about java local variable

Posted 13 April 2009 - 04:06 PM

hi i need some help, i have a question about how to access the local variable in in one method from the other method. is there anyway that i can do that? if so what command do i need to use? if possible please explain the mechanic of how it works. thank you very much for your time and effort, its much appriciated :) (forgot to say, i can't use static variable and the variable i am trying to access is at the method's parameter, though i can probably instantiated the variable at the parameter inside the method hmm)

This post has been edited by Novice.Chimp: 13 April 2009 - 04:16 PM

Is This A Good Question/Topic? 0
  • +

Replies To: a question about java local variable

#2 KYA   User is offline

  • Wubba lubba dub dub!
  • member icon

Reputation: 3202
  • View blog
  • Posts: 19,233
  • Joined: 14-September 07

Re: a question about java local variable

Posted 13 April 2009 - 04:19 PM

If it's a local variable created inside a method when called, then you can't, unless its the variable returned, example:

public getValue(int param)
   //local to this function
   int localVar = 3;
   param *= localVar;
   return param;

localVar goes out of scope as soon as the function returns

If you need to get a value then have whatever you need be returned by the function. However, this really doesn't make any sense because a method is designed to return something (even if its nothing). So any local variable created inside the method can never be accessed from the outside because of scope issues. UNLESS:

void functionOne(int param)
	//assign localVar to something
   //call another function perhaps
   int localVar = param *3; //or whatever
   functionTwo(localVar); //call do something with it

void functionTwo(int var)
   System.out.println("Local variable from functionOne:" + var);
   //do stuff

edit: Although technically, calling a function with a localVar from another function doesn't really give you the variable itself, only a copy of it.

This post has been edited by KYA: 13 April 2009 - 04:20 PM

Was This Post Helpful? 1

#3 pbl   User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8378
  • View blog
  • Posts: 31,956
  • Joined: 06-March 08

Re: a question about java local variable

Posted 13 April 2009 - 04:21 PM

you just can't
local variables are called local variables because they are local to the method they belong to
if you want them to be shared between multiple methods you have to make them instance variables
Was This Post Helpful? 1

Page 1 of 1