+ 1
Please check out this code
public class apples{ public static void main(String[]args){ int i = 1; mango(); } public static void mango{ System.out.println(i); } } // how to make int i a global variable???? https://code.sololearn.com/cxKgmydp27Qc/?ref=app
9 Answers
+ 5
@surya No , outside of main , in the beginning of the class .
public class Test
{
//global variables
static int j , k ;
// main function
public static void main (){
}
}
+ 16
You have to declare i as a static variable before the main() method. Sorry, I just forgot to tell ya'
+ 15
You can use the static keyword for making it a global variable :
public static int i = 1;
Now you can access i from anywhere you want :)
+ 14
Static keyword makes a variable/function shared between all instances of that class, not the actual objects themselves. So if you have a variable:
public static int i = 1; and if you make any changes in one instance, the changes will be reflected in all instances of that class.
+ 4
@Davye I don't think if static will make it global , atleast for that code he wrote it doesn't work :-P
@Surya. Declare public static int i ; above main to make it global
public class Program {
static int i ;
public static void main(String []args){
i = 1 ;
cool();
}
public static void cool(){
System.out.println(i) ;
}
}
+ 1
Thanks @Dayve..as I understand public makes it accessible to all the classes..but what does static do?
+ 1
@Utkarsh..so I would be needing to declare variables in main if I want it to be global...ok
+ 1
Thanks guys..corrected the bug..a java program starts with the main function, correct?.So if I declare a static variable i before a main function, how can it read it?
0
thanks @Davyve!! Please do check out the code above. I'm getting 3 errors..