Monday 24 November 2014

Beginning Programming
Methods
We saw that methods allow us to define behaviour of objects - in this section we take a closer look at methods. In our first program, we wrote our code inside the main method. The main method is a special method in a Java application and the one where execution of a Java program starts. In object oriented programming, it is good practice to write methods to implement the business logic. Methods allow us to break a complex task into simpler ones, with methods providing the implementation of the simpler ones. Since a method must implement logic, it needs input (usually, but not necessarily) and it produces output. The inputs to a method are supplied by itsparameters or arguments and the output is reflected in its return value. This is the syntax to declare a method in Java
[access] returnType methodName([arguments…]) {
//method body
}
For example to write a method that prints "HelloWorld", instead of writing the code in the main method,
we can create a method called printString that takes a String as argument and will print the argument.
This method returns nothing, so its return type is void.
void printString(String str){
System.out.println(str);
}
The advantage of this approach is that by changing the value passed as the argument, 
I can print any message I want. This is just a basic introduction to methods, we will see more about them
by and by.

No comments:

Post a Comment