importance of using methods in creating java programs?

Status
Not open for further replies.
5 comments
To initialize object from class
you need a reference of class with "new" keyword like this

class object name=new class();
ex: NewCustom cusObj=new NewCustom();
now you can use any variable form class with this object.
 
your title and thread question differs ....

methods help to categorize some piece of code or do same operation repeatedly by different values ... creating object out of class is already answered ^.^
 
Read "Head First JAVA" from O'reilly ( 2nd edition ).
It's what we get at Computer Science and it's really really fun to read.

I've just flipped a random page and this is what it said:
[SLIDE]http://eih.bz/s1/2013013116.jpg[/SLIDE]
 
Good question there.

A method is a collection of statements that are grouped together to perform an operation. It helps you a lot in finding and calculate many tasks without needing of declaring the same variables and other stuffs. For example, you can create your own method for finding the maximum number between a group of numbers, and to output the result at anytime you just write the method name, which let's say it's "max" and find the max. number easily.

There are methods that they are already built in Java, like using Math class and find the double tangent by using this: Math.tan , or you can use the random method. It also may help you in big programs which require you the same operation in many steps, so you use methods in this case.

In general to create a method, you need to follow this syntax:
modifier returnValueType methodName(list of parameters) {
// Method body;
}

To make it simple to you and see the benefit of using methods while you coding, here you are the code for the max.:
/** Return the max between two numbers */
public static int max(int num1, int num2) {
int result;
if (num1 > num2)
result = num1;
else
result = num2;

return result;
}

This method takes two parameters which they are here num1 and num2

now to call that method, you need to declare a new variable and write as this: int larger = max(30, 40);

The result will be of course: 40 :)

I hope you understand ^_^
 
Status
Not open for further replies.
Back
Top