H
H
hh42015-09-16 07:51:56
Java
hh4, 2015-09-16 07:51:56

How to use a variable from one java file on another?

"1.java" has a variable "x"(string). how to use this "x" on "2.java"?

Answer the question

In order to leave comments, you need to log in

4 answer(s)
Z
Zakharov Alexander, 2015-09-16
@AlexZaharow

Your question is a bit odd, but it's understandable. Let's not 1/2.java (because class names must match file names, and in java classes cannot be named numbers), but at least First.java and Second.java
In Second.java, write first
import First;
and further on the code in Second.java write
x=First.var1
This is if var1 is static. Otherwise, you would first have to instantiate the First object and then call access to var1 on behalf of the instance.
Although personally it seems to me that you have just started learning java. See section Scopes, Modularity, your question is from there.

D
Danil Antoshkin, 2015-09-16
@TwerTrue

You can pass it to the constructor when creating an instance of class 2

public class Main {
    
    static String x = "Тут ваша строка";
    
    public static void main(String[] args) {
        Main2 Main2 = new Main2(x);
    }
}

public class Main2 {

    String x;

    public Main2(String x) {
        this.x = x;
        Main.x = x; // Это второй вариант но только если переменная static
    }
}

Here, to be honest, there are 2 ways due to the fact that the variable is static

I
iceglen, 2015-09-16
@iceglen

packagefoo;
Have you heard of packages?

T
Tatiana, 2021-04-01
@P_TN

If in 1.java the static variables "x"(string), and 1 and 2 are in the same package,
then you can access the first class directly from the second class: just write in the second 1.x

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question