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, how should make this possible?
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();
}
}