Home Is it possible to initialize variables outside of a class?
Reply: 3

Is it possible to initialize variables outside of a class?

D.Bronson
1#
D.Bronson Published in 2017-09-11 17:33:20Z

EDIT: is it possible or usefull to initialise variables outside of a class? for example if I have a code like this:

static int example = 1;

public class test {

public static void main(String []args) {
System.out.println("I have " + example + " question!");
}

or is it more usefull to do it just like that:

public class test {
static int example = 1;

public static void main(String []args) {
System.out.println("I have " + example + " question!");
}

if both ways are possible, what are the differences? thank you in advance

kevenlolo
2#
kevenlolo Reply to 2017-09-11 17:42:36Z

In Java, declaring variable outside the class declaration is not allowed and will result to compilation error.

You must go with the second code snippet that you've posted. Below is the edited version of your code to make it work:

public class test {
   private static int example = 1;

   public static void main(String []args) {
      System.out.println("I have " + example + " question!");
   }

}

Arnav Borborah
3#
Arnav Borborah Reply to 2017-09-11 17:44:39Z

No neither of your snippets will work. The first will not work because Java does not have global variables and the second won't work because main is static and static methods cannot access class variables that aren't static

nagendra547
4#
nagendra547 Reply to 2017-09-11 18:13:11Z

Because Java doesn't support global variables. Java was designed with OOPS principals in mind and as such, every variable in Java is either local or a member of a class.

So you cannot declare variables outside of class.

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.462959 second(s) , Gzip On .

© 2016 Powered by cudou.com design MATCHINFO