Hi guys,

Im pretty new to programming so bear with me if you think this is baby stuff:P

Ive just been introduced to methods last weeks and after a week of study Im no better at understanding them.

The problem is I just seem to grasp how to you them or how the syntax works with them, i.e. If I wanted to write a method that say returned a random value.

Basically I could just really use some adivce on methods and how to try and undertsnad them and understand how to use them.

Thanks a million for any help:)

Recommended Answers

All 8 Replies

methods are operations. for example, say you have a car. what operation would you want to perform on a car? e.g. drive, refuel, checkMileage, brake, etc. basically thats it. you use methods on objects. in this case, car would be the class, and perhaps Lambhorgini Murciealago would be the object, which is instantiated from the car class..

Ok that makes quite a bit of sense,

Do you think you could give me an example of a working method?

Just something simple to help me get it?


public class Number
	//this variable is non static, therefore it needs an instance of Number
	//to hold it, all the different instances have different theNumber
	//variables inside them
	public int theNumber;
	//this variable is static, all the numbers have the same count variable, a
	//number doesnt even have to be created (if it wasnt private you could say
	//Number.count++; without ever using new Number(2);
	private static int count = 0;
	public Number(int integer)
		this.theNumber = integer;

                //this increases the static count variable shared between all the numbers, every time
                //the constructor is called, the same count variable is increased!
	//these methods are non static, they can be accessed through number.addThisToMe(annotherNumber)
	//where annotherNumber and number were created like this: Number number = new Number(2);
	public void addThisToMe(Number number)
		this.theNumber += number.theNumber;
	//annother non static method, that prints out the instances value
	public void printOutMe() {
		System.out.println("I am: " + theNumber);
	//this is a static method, its independent of instances like the count variable
	public static int getCount()
		return count;
	//the main method is allways static, as its started before you create any instances of
	public static void main(String args[])
		//lets find out how many numbers we have:
		System.out.println("Count: " + Number.getCount());
		//we create an instance of number;
		Number number1 = new Number(4);
		Number number2 = new Number(3);
		//now, what's happened to our count:
		System.out.println("Count: " + Number.getCount());
		//lets call our usefull non static method to add number2 to number1:

some code i just wrote to try and explain static and non static methods to someone. It might be a bit much with the static, but worth a peek maybe?

maybe thats a bit too advanced :/

here is a car example:

class Car
	double speed;
	public int getWheelCount()
		return 4;
	public void setSpeed(double toThis)
		speed = toThis;
	public static void main(String args[])
		//make some new cars
		Car slowCar = new Car();
		Car fastCar = new Car();
		//use some methods!
		System.out.println("Car has " + slowCar.getWheelCount());

God I still cant understand it:/

Is there no hope for me?:P

well, it took me a stupidly long time to get static methods - I remember not having a clue about them and now I just can't get my head arround not understanding them... I dont know where I finally got it, just started using them one day and could do it!

Methods are used all the time though, so unless you are confused but functional (in which case you will learn the more you use) its going to be tough.

Try making a class, can you do that? Then try making a method in it - an Employe class with a printName() method seems a reasonable place to start, just give it a go copying examples. If you can make horrible messy methods that you have to ask for help with every time, good - in a week of making little classes with bad methods you wont need to ask for help anymore, dont know what public is? just bung it in and hope it works - when you eventually need to know, you can look it up

A method of a class is simply an operation that class can perform. It's a block of code that operates on a set of data to achieve a specified result.

Methods are a way of bundling a piece of functionality into a package, which can be called on as the maker of the method allows. (more on that another time - that'll be access modifiers, which include "public", "private", and "protected")
Sussman and Abelson liken this sort of business to casting spells: you take an action that you want to perform, and you specify how to do it, and then you give it a name. Anyone who can call on that bundle by the right name can cast that spell. It's a good analogy.

The anatomy of a method is simple: it consists of a header plus a body.
The header has some optional modifiers, a required return type, and a method signature, which consists of a name and a set of formal parameters.

The modifiers include access modifiers (public, private, protected) which specify which classes may call this method. Public methods can be called from anywhere, private methods can be called only from within this class (some complications elided) and protected methods can be called from classes within this package. For now, go ahead and use "public" for everything - you'll learn about the others presently.
Other modifiers include "static" - this indicates that this method pertains to the class, and not to any particular instantiation of this class. Pursue this another day.

The return type can be any valid type, including the primitives (int, double, boolean, char, etc.) or any object type (String, Integer, PersonType) that your code knows about, or void. The return type specifies what sort of value the method will return, if any. (If none, the return type must be void - some return type must be specified.

The method signature is what the compiler uses to locate the method within the class. It consists of a name, which must obey the standard restrictions on naming, ie, it can't conflict with reserved words and it can't start with a number, yada yada, plus a list of formal parameters. The formal parameters tell you what this method requires when called. They are a local variable declaration - the formal parameters are local variables in the method, but the assignment is made for you, when the method is called. Notice that you can have two, three, or many methods called "Foo" in a given class, as long as their formal parameters differ. This is called overloading - again, follow up on this another day, but notice that the method must be uniquely identified within its class by name+parameters.

The method body is a sequence of Java statements surrounded by curly braces: {}
Any legal code can go in there, including an empty block. Any variables declared within those braces, along with the formal parameters, have local scope: they only exist within those curly braces. The method also has access to the class fields - variables declared at the top level of the class, outside of any method - it can read them or modify them, and those modifications persist after the method completes.

As an example, here's something from a piece of code I'm cobbling together now, lives in a class called GUI.java:

public JPanel showFiles(PHPDir root)
JPanel p = new JPanel(); // make a JPanel object
// recursively descend from "root" and add all the files to the panel
return p;

public indicates that this can be called by any object which has a reference to a GUI object.
JPanel indicates that it returns a JPanel - that a call to this method, for all intents and purposes, is equivalent to a reference to a JPanel
showFiles is the name of the method, because it shows the files in a directory.
(PHPDir root) tells us that it expects an object of type PHPDir, which will locally be known as "root".

This method has no side effects, so its only effect is the return value. Therefore a call of this method will look something like

JPanel directoryPanel = showFiles(r);


JFrame directoryFrame;
directoryFrame.add (showFiles(r));

Methods with a void signature are used only for their side effects: they typically change some field of an object - ie, car.setSpeed(75) - or trigger some event - ie, System.haltAndCatchFire().

I hope that clears up more than it confuses. If it sparks more questions, that's a good thing. If it makes you feel like you'll "never understand this stuff" then it's terrible and should be ignored.

commented: Very good and detailed. +4

Thank you guys for all your input and help.

Im going to study this page until my face turns blue and I understand methods.


Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.