public class StringMassive { StringMassive helper = new StringMassive(); public static void main (String[] args) { //helper.receiver(String s); ошибка } public void massive() { String[] names = {"Антон", "Дмитрий", "Пётр"}; helper.receiver(names[0]); } public void receiver(String s) { System.out.println(s); } } 

Stuck on nonsense, please tell me. I have an array of names located in the massive() method. I select the zero element Anton from the array and pass it to the reciver(String s) method. How can I get the Anton element in the main method?

  • You are trying to declare an instance of the String class in a method parameter. Or did I not understand your idea? - SlandShow 2:21
  • I tried to pass the names[0] argument to the reciver method. For a method to accept it, I must declare a parameter of this method of type String (the same as the passed argument names[0] ). So I wrote String s . Can you do without it? - Kojer Defor

3 answers 3

1 way

 static Main helper = new Main(); public static void main (String[] args) { helper.massive(); } public void massive() { String[] names = {"Антон", "Дмитрий", "Пётр"}; receiver(names[0]); } public void receiver(String s) { System.out.println(s); } 

2 way

 public static void main (String[] args) { massive(); } public static void massive() { String[] names = {"Антон", "Дмитрий", "Пётр"}; receiver(names[0]); } public static void receiver(String s) { System.out.println(s); } 

3 way

 public static void main (String[] args) { new Main().massive(); } public void massive() { String[] names = {"Антон", "Дмитрий", "Пётр"}; receiver(names[0]); } public void receiver(String s) { System.out.println(s); } 
  • Thank you very much. It is very unusual to call methods without any reference. Is this a normal practice? - Kojer Defor
  • @KojerDefor links to what? are you talking about this ? if yes, then you cannot refer from the static context (the method in this case) - Senior Pomidor

The code in question is not working. StringMassive helper = new StringMassive(); will lead to endless recursion of creating new StringMassive objects. Make the helper local variable in main :

 public class StringMassive { public static void main (String[] args) { StringMassive helper = new StringMassive(); System.out.println(helper.receivedValue); helper.massive(); System.out.println(helper.receivedValue); } public void massive() { String[] names = {"Антон", "Дмитрий", "Пётр"}; this.receiver(names[0]); } public String receivedValue; public void receiver(String s) { this.receivedValue = s; System.out.println(s); } } 
  • The variable helper not static, I cannot call it from the main method. And if I stick an object into the main method, then the massive method will not be able to use the helper link. - Kojer Defor

Well, you call the receiver method, call massive () , it will show you what you wanted.