Thursday, 18 August 2011

Java: Methods, Returning Values and the Void type

In Java, a method is a series of statements separate from everything else in the program, given it's own name. This allows it to be referenced later. We used methods (or functions) in earlier examples for ease. It allowed us to perform actions without having to think about the internal working of the method, so in this way, it shares similarities with the concept of abstraction.

public void greet() {

System.out.println("Hi, there!");
System.out.println("How are you today?");


In the above example, we have a method named "greet", and the brackets immediately proceeding show that it takes no parameters (More on that next time, basically input to change how the function works). Preceding the name is "public void", public stating who can use the function (encapsulation), and the type of the returned value, which we'll talk about shortly.

The body of the method simply prints out 2 lines of text, which can now be printed out more simply by calling this method.


Since the method needs to be part of a class object (Java being an object oriented language), the object which it's a part of must be created, and then the method can only be called as a function of the object, as shown above.

On top of being an abstraction to hold a group of statements, methods are used to compute values, and return a value in place of that method. Assuming we had a method, "calculateHeight" as part of the object exampleObject, we could have:

int i = exampleObject.calculateHeight();

Then, stored in i is the value gained through the function. To have a method return a value, or a string, we need to state the type it returns when declaring it, and have a return statement at the end of it.

public int calculateHeight(){

//Do stuff...
return someInt;

If someInt is not calculated, or is not an integer type, your compiler will freak out and throw some errors at you, so always test and double check. Another difference to the previous method is instead of void, we have int. This is the type of the return value, but as in the previous method, a return value isn't always needed, so instead of creating a different method type for this case, or forcing the user to simply return 0 all the time, as some other languages do, there is just the void type. Nothingness.

No comments:

Post a Comment