'How to initialize global variable in method
static void compare(int a) {
Scanner sc= new Scanner(System.in);
int b= sc.nextInt();
i want to make int b to global variable.
in Python i can initialize global variable in a function like this
def compare():
global b
b = 15
but in java adding static
static int b= sc.nextInt(); makes error, why?
Solution 1:[1]
If you want to make some variable global then you would need to declare the variable outside the method. In java, you cannot declare static variables inside method (even if it is static) because inside method all variables are local variables that has no existence outside this method thats why they can't be static.
import java.util.*;
public class GlobalVariable{
static int b;
public static void main(String...args){
GlobalVariable.compare(1);
System.out.println(b);
}
static void compare(int a){
Scanner sc = new Scanner(System.in);
b = sc.nextInt();
}
}
Solution 2:[2]
To my knowledge, you cannot do this. You would have to declare b outside of the method.
static int b ;
Then inside of the method you initialise it :
b= sc.nextInt();
Refer to this: Global variables in Java for more details about global variables in JAVA and when to use/not use them.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Madhav |
| Solution 2 | Jason Barbour |
