0% found this document useful (0 votes)
3 views

Defining+Methods

Methods in Java

Uploaded by

Zhou Crance
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Defining+Methods

Methods in Java

Uploaded by

Zhou Crance
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 5

Methods

De ning Methods
fi
The Syntax


public final void printName(String name) throws InterruptedException { }

access return exception


modi er type (optional)

optional method signature method


speci er (name & parameters) body
fi
fi
// method signature must follow the return type

public void final printName();

=> DOES NOT COMPILE

// return type can be any primitive or object

public int addNumbers (int a, int b) {

return a + b;

System.out.println(addNumbers(2, 3));

=> 5

public int addNumbers (int a, int b) {

long c = 1L;
// return type must be consistent

public int addNumbers (int a, int b) {

long c = 1L;

return c * (a + b);

=> DOES NOT COMPILE


To keep in mind...
• method name is Java identi er (same rules as variable names)
• parameters in parameter list are separated by comma
• after throws there can be more than one exception, separated by comma
• method must have a body { }, even if it is empty

public void doNothing() {} // OK


fi

You might also like