variable scope

i have a package with 2 classes (main and puzzle).  i want one variable "size" to be applicable to both classes.  I've tried using the code below. How do I "pass" the variable to the other class?  i could use the constructor but I feel that is wasteful and not necessary. is there another way?  i thought public variables were available to all classes in the package.
public class Main {

public static int size;

public Main {

public static void main(String[] args) {

size = .....



public class puzzle {

for (int i = 0; i < size; i++)...etc.
Who is Participating?
tbboyettConnect With a Mentor Commented:
Since your variable "size" is in the class main and you don't want to pass it as a parameter in the constructor, all you would need to do is call the variable in you Puzzle class like this:  Main.size

for (int i = 0; i < Main.size; i++) {

CEHJConnect With a Mentor Commented:
It doesn't have to be public. Since your classes are in the same package you could give access by using *no* modifier
ADSLMarkConnect With a Mentor Commented:
If it's a size value like in the example then it's good practice to pass this with the constructor like:
//for example
new Puzzle(size);

public Puzzle(int size)

Why is this better? Well you can instantiate the puzzle with different sizes. If there is only one size possible then do the following:

class Puzzle
public final static int SIZE = 42;

and you can access this static variable by:

For the solution to your problem self, you should say: Main.size since size is a *static* variable in the Main class and thus you need to specify the Main class before the variable.

Mayank SConnect With a Mentor Associate Director - Product EngineeringCommented:
If you dont want size to be static, you can create a getter for it:

public int getSize ()
  return size ;

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.