0
votes

I'm trying to pass a string from one class to another, but not succeeding. I realized during research and trial and error that I need to have "public static void main(String[] args) {}" to be able to use the if statement, but then getY() produces an error. What can I do differently?

public class Testing {
public static String z;
public static void main(String[] args) {
int x = 15;

if (x >= 10)
    {
    z = "Blabla";
    }
    public static String getZ() {
    return z;
    }
  }
}

The other class is

class B {
public static void main(String args[]) {
String x = Klasatest2.getZ();

System.out.println(x);
}
}

Error:

Klasatest2.java:14: illegal start of expression

public static String getZ() 

^

Klasatest2.java:14: illegal start of expression

public static String getZ() {

       ^

Klasatest2.java:14: ';' expected

public static String getZ() {

                    ^

Klasatest2.java:14: ';' expected

public static String getZ() {

                           ^

4 errors

2

2 Answers

0
votes

For starters, you can't declare a method inside of a method,

public static void main(String[] args) {
int x = 15;

if (x >= 10)
    {
    z = "Blabla";
    }
    public static String getZ() {
    return z;
    }
  }
}

So you have to make sure that get getZ() method is declared OUTSIDE of main(string[] args)

Like this,

public class Test {
public static String z;
public static void main(String[] args) {
int x = 15;

if (x >= 10)
    {
    z = "Blabla";
    }

  }
public static String getZ() {
    return z;
    }
}

Also, you shouldn't have two main(String[] args) methods, as only one of them will be called unless for some reason you decide to call it yourself, which would be very strange. So if you wanted the string to be set in class Test, you would need to call it's main method from your other class, possible like this.

Test.main(null);
0
votes

Your application can only have one main(String args[]) method. Try this:

public class Testing {
  public static void main(String[] args) {
    A a = new A("hy");
    B b = new B(a.z);
  }

  public class A {
    public String z;
    public A (String z) {
      this.z = z;
    } 
  }

  public class B {
    public B (String y) {
      System.out.println(y);
    }
  }
}