Can global variables be used inside a method? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Can global variables be used inside a method?

If I declare a variable in main for example an IP address, can I use that address in a method without passing it to the method through the call and having to rename it?

13th Sep 2016, 5:53 PM
Louis Nunez
3 Answers
+ 2
If you declare it in main, it is not global. You should avoid using global variables if possible.
13th Sep 2016, 6:07 PM
Zen
Zen - avatar
+ 1
You will need to stop using global variables ASAP. You will need to achieve a high level of "Encapsulation" by using access specifiers at all times. Find a way that makes sense to have that variable local to your method, whether you pass it as an argument or create it inside the method itself, but don't make it global, that's really bad security practice.
15th Sep 2016, 7:53 PM
Pablo Hernandez
0
why we prefer local variables?
14th Sep 2016, 6:45 AM
Fernweh
Fernweh - avatar