Question about methods | Sololearn: Learn to code for FREE!
Neuer Kurs! Jeder Programmierer sollte generative KI lernen!
Kostenlose Lektion ausprobieren
0

Question about methods

public static void main (string[] args){ int x=10; test(x); } static void test (int x){ system.out.printIn(x); } I dont understand why in the comment section people say that we should have two variables instead of one. I mean, if we have more than one methods how every method know how to comunicate correctly?. This is so confusing, i will be grateful to a clear answer. And also: why the main method always is "(string [] args)" even if we work with numbers or with another type of variable that isnt string

5th Apr 2018, 10:09 PM
Grecia Valentina Pernía Valero
Grecia Valentina Pernía Valero - avatar
3 Antworten
+ 3
I don't have a clue where your code came from or exactly what you are trying to express. However, I'm going to give an answer. If it doesn't correctly answer your question, please hit the share icon of the place you are talking about, copy to the clipboard, and paste a link here so we can see the context. The x in main is different from the x in test. The x in test is stored in a different physical memory location. It is initialized to the value of x in main. But, I can change it without having any effect on the x in main so changing the code to: public static void main (string[] args){ int x=10; test(x); System.out.println(x); } static void test (int x){ System.out.printIn(++x); } would output: 11 10 as the x in test becomes 11, while the one in main stays 10.
5th Apr 2018, 11:32 PM
John Wells
John Wells - avatar
+ 1
You have a variable called x in main() and you have a variable called x in the test(). They are different variables. The main function only knows its own x. The test function only knows its own x. If you want both functions to access the same variable x, you have to make it a class attribute instead of declaring it in the main function.
5th Apr 2018, 11:40 PM
Chris
Chris - avatar
0
I don't understand your first question, but for the last one, "string [] args" is the parameters you enter when running the program from the terminal. On linux(on other OS, the method is similar with different syntax), you may see programs like so: ./ProgramName param1 param2 In your example, the "args" parameter of the main function would contain the string "param1" as args[0] and "param2" as args[1]. What you do with that data is your thing. I'm coming from a C++ background but I guess java works the same way.
5th Apr 2018, 10:49 PM
Bebida Roja
Bebida Roja - avatar