简体   繁体   中英

what is difference between declaring variable out of main method and inside main method?

When I was reading book about Java , I saw one example written like this. And I am wondering can I declare variable in outside of main method ? What is difference between declaring variable outside and inside main method? what is " static" 's role in here ? Please some one explain to me? I am new in java.

public class Printstuff {
      static int an_integer = 0;
        public static void main(String[] args) {
          int an_integer = 2;
          String[] some_strings = {"Shoes", "Suit", "Tie" };
          an_integer = an_integer - 1;
          some_strings[an_integer] = some_strings[an_integer] +"+++";
          for (int i = 0; i < some_strings.length; i++)
            System.out.println(some_strings[Printstuff.an_integer]);
        }
    }

Best regards.

1) Inside vs Outside:

If you declare your object inside a method, it will be visible only in this method. Basically, if you put brackets around it, it's only visible/accessible from within these brackets.

If you declare your object outside the method (inside the class), it depends on the access modifier .
By default, it's visible/accessible from within that class and the whole package.

2) Static

Static means, that this Object/Variable belongs to the class itself, and not to its objects.

Example:

public class Members {

  static int memberCount;

  public Members() {
     memberCount++;
  }
}

memberCount exists only once, no matter how many Objects of the class exists. (even before any object is created!)

Every time you create a new Object of Members , memberCount is increased. Now you can access it like this: Members.memberCount

Declaring a variable in the main method will make it available only in the main. Declaring a variable outside will make it available to all the methods of the class, including the main method.

Example :

public class Foo {
   private String varOne = "Test";

   public void testOne() {
     System.out.println(varOne);
     System.out.println(varTwo); // Error, this variable is available in the testTwo method only
   }

   public void testTwo() {
     String varTwo = "Bar";
     System.out.println(varOne); // Will display "Test"
     System.out.println(varTwo); // Will display "Bar"
   }
}

I'm intrigued nobody has mentioned memory matters. Many years ago, instantiating within main() would allocate the variable to the stack, wether instantiating it out ot main would allocate the variable to the heap. Back in those days, systems had very small stacks, so not checking this detail would cause a stack overflow very easilly. I'm not an expert in memory architecture though, I wish somebody could contribute to this subtle detail as applicable to current SW architecture / memory.

There is a scope difference. And you have to declare it as static because your main function is static so it allows you to use only static variables. Variable which declares inside main method would only be used inside main method only.

Now you might wondering that why I need to have main method as static!!! As any application in java will run from main method so it can be called by class name only without creating any object so we are defining it as static. All static method can call with class reference, no object needed.

The difference is now your an_integer has more scope.

Example if you have another method.

public class Printstuff {
      static int an_integer = 0;
        public static void main(String[] args) {
          int an_integer = 2;
          String[] some_strings = {"Shoes", "Suit", "Tie" };
          an_integer = an_integer - 1;
          some_strings[an_integer] = some_strings[an_integer] +"+++";
          for (int i = 0; i < some_strings.length; i++)
            System.out.println(some_strings[Printstuff.an_integer]);
        }

      public void anotherMethod(){
         an_integer++;
      }


    }

As you declared

<default package> int an_integer=0;

All clases in the same package has access to this variable.

What you refer to is the scope of a variable.

Variables inside methods are only accessible inside this method, ie an_integer inside the main -method cannot be referenced outside the main method. Variables can even have narrower scopes, for exammple inside loops. The classic iterating variable of a for loop is only avaiable inside its loop, afterwards its gone.

Variables outside methods are called fields. It depends on its access modifier where it can be seen. Private fields for example are only avaiable inside this class, public fields can be accessed from anywhere (other access modifiers are protected and none, which falls back on a default). Basically, you can use a field inside a class to access its value from every method inside this class, this, however, might be dangerous if multiple threads access the same instance of a class, but this is a whole other story.

A field and a local variable may have the same name, which can lead to confusion. I would generally prefer not to do this, or, maybe better, always refer to fields with a this accessor. I am not entierly sure whether there is a preference of local variables versus fields of the same name, but I would guess local variables are of higher priority when determining which one was meant.

Static fields now mean that this variable does not belong to an instance of a class, but to the class itself. Static fields (and methods) can be read (or invoked) without having to initialize the class first. An example could be a standardvalue of a class, or maybe a factorymethod (if its a method). Static fields may also come in handy for constants, together with the final modifier. A public final static field is pretty much a global constant.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM