Global variables in Java

后端 未结 24 2092
青春惊慌失措
青春惊慌失措 2020-11-22 11:56

How do you define Global variables in Java ?

24条回答
  •  野性不改
    2020-11-22 12:19

    Going by the concept, global variables, also known as instance variable are the class level variables,i.e., they are defined inside a class but outside methods. In order to make them available completely and use them directly provide the static keyword. So if i am writing a program for simple arithmetical operation and it requires a number pair then two instance variables are defined as such:

    public class Add {
        static int a;
        static int b; 
        static int c;
    
        public static void main(String arg[]) {
            c=sum();
            System.out.println("Sum is: "+c); 
        }
    
        static int sum() {
           a=20;
           b=30;
           return a+b;   
        }
    }
    
    Output: Sum is: 50
    

    Moreover using static keyword prior to the instance variables enable us not to specify datatypes for same variables again and again. Just write the variable directly.

提交回复
热议问题