• Post Reply Bookmark Topic Watch Topic
  • New Topic

Can I pass a variable to to a method?  RSS feed

 
Paul Carter
Ranch Hand
Posts: 57
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I was wondering if there was a way I could pass the variable as a parameter as opposed to just the value e.g.

public void testvar () {
int testval1 = 1;
testvar2(testval1);
System.out.println(testval1); //I want this to print '2'
}

public void testvar2 (int testval) {
testval2 = 2;
}

Thanks in advance

Paul.
 
Christophe Verré
Sheriff
Posts: 14691
16
Eclipse IDE Ubuntu VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
make public int testvar2() instead.
If you want to pass it as a parameter, you could use a wrapper like the Integer class.
 
pascal betz
Ranch Hand
Posts: 547
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
no you can not pass by reference.
You could do:


instead (using return value instead of void).

Or you can pass in a Mutable Object and modify the state of the Object.




Just two ways how you could do it... you have to decide which/why/what... :-)


pascal
 
pascal betz
Ranch Hand
Posts: 547
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

If you want to pass it as a parameter, you could use a wrapper like the Integer class.


Integer is imutable.

pascal
 
Christophe Verré
Sheriff
Posts: 14691
16
Eclipse IDE Ubuntu VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Integer is imutable.

My miss
Thanks for pointing it out.
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The wrapper direction is good, but you'd have to make your own mutable structure.

Method2 cannot change the holder variable to point to a different IntHolder, but it can change the contents of the IntHolder that both methods have reference to.
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24217
38
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Lazy /me will generally use a one-element array instead of an "XHolder" class.
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
D'oh, that is a lot cleaner, fer sure.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!