What is print in the main method? I just don't quite understand how we go from
public static void main(String[] args) {
print("Java is easy to learn!");
print("Java opens many opportunities!");
}
to
public static void print(String s) {
//My code goes here.
}
Is print an object? Is the text declared in print, in the main method then attached to print() in the Solution class? Then when print is put as the method name in the second method, how does print(String s) get the "Java is easy to learn!" and "Java opens many opportunities" attached to the s variable? I just don't get the process and it makes it much harder for me to know what to do on my own.
Question about print in the main method.
Under discussion
Comments (3)
- Popular
- New
- Old
You must be signed in to leave a comment
Guadalupe Gagnon
10 April 2019, 19:55
public static void main(String[] args) {
print("Java is easy to learn!");
these is a method call, you can tell because it is a word followed by parentheses
print("Java opens many opportunities!");
the method name is outside the parentheses, while parameters are inside the parentheses
in this case the parameters are 1 string
}
↑ the main method is the entry part of your program. It is run starting on the first line when you run the program and proceeding in order. When a method is called, the code jumps to the method and executes the code contained within then jumps back to the next line following where the method was called
This is a method declaration. I won't go into too much details, as you will be learning more about this in subsequent lessons and levels. What is required is the word static, the return type, method name, and method parameters. (static is not 'required', but for the next few levels will be required. Just make sure you add it for now)
In this method void is the return type, which just means it returns nothing, print is the method name (and you can name them whatever you want as long as the name is free), and the parameters are contained inside the parentheses. To call a method from other code you need to match the name and parameters or the code will not compile.
↓ return type here
public static void print(String s) {
↑ method name followed by parameters
}
Whatever value is passed into the parameter from the calling code will become the variable in the parameter of the method.
So to successfully call this code your code would look like one of these:
String x = "a random variable string";
print("a random string literal");
print(x);
+2
Connor
10 April 2019, 20:59
THANK YOU! That helped a lot I really appreciate it!
+1
Guadalupe Gagnon
10 April 2019, 22:09useful
I think of methods like little bits of repeated code. You can write all the repeat lines, which can be just a few lines to 100's, in a method; then whenever you need that code you can call methods from other methods, and even call methods from themselves. This last bit is interesting and called recursion. Take this bit of code for example:
+1