• Post Reply Bookmark Topic Watch Topic
  • New Topic

Passing an array to a method in the same class?  RSS feed

 
Peter Netting
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Is it possible to pass an array in a class to a method of the same class. Or is this bad programming?

The compiler complains about this example bit of code:
test.java(7): Can't make static reference to method void displayArray(int[]) in test

public class test
{
public static void main(String[] args)
{
int array[] = {0,1,2,3,4,5,6,7,8,9};

displayArray(array);
}
void displayArray(int values[])
{
for (int i = 0; i < values.length; i++)
{
System.out.println(values[i]);
}
}
}
 
Peter Netting
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Sorry,
I'll answer my own question.
Need an instance of the class to invoke the method. ie:
public class test
{
public static void main(String[] args)
{
int array[] = {0,1,2,3,4,5,6,7,8,9};

test t = new test();
t.displayArray(array);
}
void displayArray(int values[])
{
for (int i = 0; i < values.length; i++)
{
System.out.println(values[i]);
}
}
}
 
Maria Kowalczyk
Greenhorn
Posts: 15
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Or you could just make displayArray() method static.
 
Campbell Ritchie
Marshal
Posts: 56584
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Maria Kowalczyk wrote:Or you could just make displayArray() method static.
Possibly. It looks like something which might be needed again, so it would be better as a static member of a different class. Create a utility class to contain that sort of method.
 
Paweł Baczyński
Bartender
Posts: 2087
44
Firefox Browser IntelliJ IDE Java Linux Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yeah I also like replying to posts from previous millennium ;)
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!