Friday, September 4, 2015

Methods in Java

Methods in Java are used to make code easier to read and to make sure that code is not duplicated. Code that needs to be run over and over again is placed in a method, which is just a sequence of instructions all placed together in one spot. This is basically what methods are, but it's important to make sure we've got the details nailed down. In other words, you need to know how methods in Java truly work so that you know how to best use them.
Methods in Java have their own scope. What is method scope? Scope is what you can see.
Anything inside of a method in Java is inside of the method's scope. When Java is executing code inside of a method, it's scope is limited to whatever is inside that method. It cannot look beyond the method. So what exactly do I mean?

Variables can be created anywhere in your program. You typically create variables inside of methods, such as the main method, or some other Java method that you create. Here's an example of a program with two methods, and it has variables being created inside of each method. We're going to see which variables a program can see depending on which part of the code your program is executing.

There are variables created in the main method, and there is a variable created in otherMethod(), another Java method. When the program is inside the main method, it can print out the values of num and pi, because they are still within the scope of the method. Try printing out the value of num inside  otherMethod().

Notice how in my example, my compiler in Eclipse is showing me that I have an error when I try to print out the value of num when I'm inside otherMethod(). This is because there is no way to see the variable num from within another method besides the main. So, it is said to be out of scope. The same is true if I try to print out the value of num2 inside of the main method.
Inside the main method, Java can't see any variables created in other methods.
Get rid of the lines of code that have errors in them, and run the program.

You'll see that only two of the println's actually worked. What happened to the third one? Remember, Java programs start at the top of the main method. This means that Java starts executing code beginning with the first line it finds inside of the main method. Java creates the num variable, the pi variable, prints out the num variable, prints out the pi variable, and then reaches the end of the main. When that happens, the program finishes. It never gets to the other method, so it never printed out the value of num2. It never even created the num2 variable!



No comments:

Post a Comment