Back

Explore Courses Blog Tutorials Interview Questions
+11 votes
5 views
in Java by (900 points)
I am fairly new to Java, I wanted to know how can i define a global variable ?

2 Answers

+11 votes
by (13.2k points)

To define a Global variable in java, the keyword static is used. Java actually doesn’t have the concept of Global variable, it is known as class variable ( static field ). These are the variables that can be used by the entire class.

Example -

public class Library {

          private String userName ; // instance variable, specific to a Library

          private static int userId ; // class variable

          // constructer used to initialise a Student object.

         public Library(String userName) {

                   this.userName = userName ;

         }

        public static incrementuserId( ) {

                   userId++;

}

}

0 votes
by (32.3k points)

To define the Global Variable, you can just use the static Keyword like this:

public class Example {

    public static int a;

    public static int b;

}

Now, you can access variable a and b from anywhere by calling like this:

Example.a;

Example.b;

Want to learn Java from scratch! Here's a video for beginners in Java:

Related questions

0 votes
1 answer
asked Sep 19, 2019 in Java by Anvi (10.2k points)
0 votes
1 answer
asked Aug 1, 2019 in Java by Aarav (11.4k points)
0 votes
1 answer

Browse Categories

...