+ 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

16th Jun 2017, 5:08 AM
suryapoojary
suryapoojary - avatar
9 Réponses
+ 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 (){ } }
16th Jun 2017, 6:50 AM
Utkαrsh
Utkαrsh - avatar
+ 16
You have to declare i as a static variable before the main() method. Sorry, I just forgot to tell ya'
16th Jun 2017, 7:44 AM
Dev
Dev - avatar
+ 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 :)
16th Jun 2017, 5:31 AM
Dev
Dev - avatar
+ 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.
16th Jun 2017, 5:38 AM
Dev
Dev - avatar
+ 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) ; } }
16th Jun 2017, 6:09 AM
Utkαrsh
Utkαrsh - avatar
+ 1
Thanks @Dayve..as I understand public makes it accessible to all the classes..but what does static do?
16th Jun 2017, 5:33 AM
suryapoojary
suryapoojary - avatar
+ 1
@Utkarsh..so I would be needing to declare variables in main if I want it to be global...ok
16th Jun 2017, 6:34 AM
suryapoojary
suryapoojary - avatar
+ 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?
16th Jun 2017, 6:47 AM
suryapoojary
suryapoojary - avatar
0
thanks @Davyve!! Please do check out the code above. I'm getting 3 errors..
16th Jun 2017, 5:40 AM
suryapoojary
suryapoojary - avatar