0% found this document useful (0 votes)
62 views15 pages

Java Methods: Definition and Examples

The document discusses methods in Java. It explains that methods are blocks of code that are declared within a class and can be called multiple times. Methods can take parameters and return values. The document provides examples of creating methods, calling methods, overloading methods, and using recursion with methods. It also covers method scope and how variables are accessible within methods and blocks.

Uploaded by

Hestia HD
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
62 views15 pages

Java Methods: Definition and Examples

The document discusses methods in Java. It explains that methods are blocks of code that are declared within a class and can be called multiple times. Methods can take parameters and return values. The document provides examples of creating methods, calling methods, overloading methods, and using recursion with methods. It also covers method scope and how variables are accessible within methods and blocks.

Uploaded by

Hestia HD
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

A method is a block of code which only runs when it is called.

You can pass data, known as parameters, into a method.

Methods are used to perform certain actions, and they are also known
as functions.

Why use methods? To reuse code: define the code once, and use it many
times.

Create a Method
A method must be declared within a class. It is defined with the name of the
method, followed by parentheses (). Java provides some pre-defined methods,
such as [Link](), but you can also create your own methods to
perform certain actions:

Example
Create a method inside MyClass:

public class MyClass {

static void myMethod() {

// code to be executed

Example Explained
 myMethod() is the name of the method
 static means that the method belongs to the MyClass class and not an
object of the MyClass class. You will learn more about objects and how to
access methods through objects later in this tutorial.
 void means that this method does not have a return value. You will learn
more about return values later in this chapter
Call a Method
To call a method in Java, write the method's name followed by two
parentheses () and a semicolon;

In the following example, myMethod() is used to print a text (the action), when it


is called:

Example
Inside main, call the myMethod() method:

public class MyClass {

static void myMethod() {

[Link]("I just got executed!");

public static void main(String[] args) {

myMethod();

// Outputs "I just got executed!"

Run example »

A method can also be called multiple times:

Example
public class MyClass {
static void myMethod() {

[Link]("I just got executed!");

public static void main(String[] args) {

myMethod();

myMethod();

myMethod();

// I just got executed!

// I just got executed!

// I just got executed!

Run example »

In the next chapter, Method Parameters, you will learn how to pass data
(parameters) into a method.

Parameters and Arguments


Information can be passed to methods as parameter. Parameters act as
variables inside the method.
Parameters are specified after the method name, inside the parentheses. You
can add as many parameters as you want, just separate them with a comma.

The following example has a method that takes a String called fname as


parameter. When the method is called, we pass along a first name, which is
used inside the method to print the full name:

Example
public class MyClass {

static void myMethod(String fname) {

[Link](fname + " Refsnes");

public static void main(String[] args) {

myMethod("Liam");

myMethod("Jenny");

myMethod("Anja");

// Liam Refsnes

// Jenny Refsnes

// Anja Refsnes

Run example »
When a parameter is passed to the method, it is called an argument. So,
from the example above: fname is a parameter,
while Liam, Jenny and Anja are arguments.

Multiple Parameters
You can have as many parameters as you like:

Example
public class MyClass {

static void myMethod(String fname, int age) {

[Link](fname + " is " + age);

public static void main(String[] args) {

myMethod("Liam", 5);

myMethod("Jenny", 8);

myMethod("Anja", 31);

// Liam is 5

// Jenny is 8

// Anja is 31

Run example »
Note that when you are working with multiple parameters, the method call must
have the same number of arguments as there are parameters, and the
arguments must be passed in the same order.

Return Values
The void keyword, used in the examples above, indicates that the method
should not return a value. If you want the method to return a value, you can
use a primitive data type (such as int, char, etc.) instead of void, and use
the return keyword inside the method:

Example
public class MyClass {

static int myMethod(int x) {

return 5 + x;

public static void main(String[] args) {

[Link](myMethod(3));

// Outputs 8 (5 + 3)

Run example »

This example returns the sum of a method's two parameters:

Example
public class MyClass {
static int myMethod(int x, int y) {

return x + y;

public static void main(String[] args) {

[Link](myMethod(5, 3));

// Outputs 8 (5 + 3)

Run example »

You can also store the result in a variable (recommended, as it is easier to read
and maintain):

Example
public class MyClass {

static int myMethod(int x, int y) {

return x + y;

public static void main(String[] args) {

int z = myMethod(5, 3);

[Link](z);

// Outputs 8 (5 + 3)

Run example »
A Method with If...Else
It is common to use if...else statements inside methods:

Example
public class MyClass {

// Create a checkAge() method with an integer variable called age

static void checkAge(int age) {

// If age is less than 18, print "access denied"

if (age < 18) {

[Link]("Access denied - You are not old enough!");

// If age is greater than 18, print "access granted"

} else {

[Link]("Access granted - You are old enough!");

public static void main(String[] args) {

checkAge(20); // Call the checkAge method and pass along an age of 20

}
// Outputs "Access granted - You are old enough!"

Method Overloading
With method overloading, multiple methods can have the same name with
different parameters:

Example
int myMethod(int x)

float myMethod(float x)

double myMethod(double x, double y)

Consider the following example, which have two methods that add numbers of
different type:

Example
static int plusMethodInt(int x, int y) {

return x + y;

static double plusMethodDouble(double x, double y) {

return x + y;

public static void main(String[] args) {

int myNum1 = plusMethodInt(8, 5);


double myNum2 = plusMethodDouble(4.3, 6.26);

[Link]("int: " + myNum1);

[Link]("double: " + myNum2);

Run example »

Instead of defining two methods that should do the same thing, it is better to
overload one.

In the example below, we overload the plusMethod method to work for


both int and double:

Example
static int plusMethod(int x, int y) {

return x + y;

static double plusMethod(double x, double y) {

return x + y;

public static void main(String[] args) {

int myNum1 = plusMethod(8, 5);

double myNum2 = plusMethod(4.3, 6.26);

[Link]("int: " + myNum1);

[Link]("double: " + myNum2);

}
Run example »

Note: Multiple methods can have the same name as long as the number and/or
type of parameters are different.

Java Scope
In Java, variables are only accessible inside the region they are created. This is
called scope.

Method Scope
Variables declared directly inside a method are available anywhere in the
method following the line of code in which they were declared.

Example
public class MyClass {

public static void main(String[] args) {

// Code here cannot use x

int x = 100;
// Code here can use x

[Link](x);

Run example »

Block Scope
A block of code refers to all of the code between between curly braces {}.
Variables declared inside blocks of code are only accessible by the code between
the curly braces which follows the line in which the variable was declared. A
block of code may exist on its own or it may belong to
an if, while or for statement. In the case of for statements, variables
declared in the statement itself are also available inside the block's scope.

Example
public class MyClass {

public static void main(String[] args) {

// Code here CANNOT use x

{ // This is a block

// Code here CANNOT use x

int x = 100;

// Code here CAN use x


[Link](x);

} // The block ends here

// Code here CANNOT use x

Run example »

Java Recursion
Recursion is the technique of making a function call itself. This technique
provides a way to break complicated problems down into simple problems which
are easier to solve.

Recursion may be a bit difficult to understand when encountering it for the first
time, the best way to figure out how it works is to experiment with it.

Recursion Example
Adding two numbers together is easy to do, but adding a range of numbers is
more complicated. In the following example, recursion is used to add a range of
numbers together by breaking it down into the simple task of adding two
numbers:

Example
Use recursion to add all of the numbers up to 10.

public class MyClass {

public static void main(String[] args) {

int result = sum(10);

[Link](result);

public static int sum(int k) {

if (k > 0) {

return k + sum(k - 1);

} else {

return 0;

Run example »

Example Explained
When the sum() function is called, it adds parameter k to the sum of all numbers
smaller than k and returns the result. When k becomes 0, the function just
returns 0. When running, the program follows these steps:

10 + sum(9)
10 + ( 9 + sum(8) )
10 + ( 9 + ( 8 + sum(7) ) )
...
10 + 9 + 8 + 7 + 6 + 5 + 4 + 3 + 2 + 1 + sum(0)
10 +9+8+7+6+5+4+3+2+1+0

Since the function does not call itself when k is 0, the program stops there and
returns the result.
Halting Condition
Just as loops can run into the problem of infinite looping, recursive functions
can run into the problem of infinite recursion. Infinite recursion is when the
function never stops calling itself. Every recursive function should have a halting
condition, which is the condition where the function stops calling itself. In the
previous example, the halting condition is when the parameter k becomes 0.

It is helpful to see a variety of different examples to better understand the


concept. In this example, the function adds a range of numbers between a start
and an end. The halting condition for this recursive function is when end is not
greater than start:

Example
Use recursion to add all of the numbers between 5 to 10.

public class MyClass {

public static void main(String[] args) {

int result = sum(5, 10);

[Link](result);

public static int sum(int start, int end) {

if (end > start) {

return end + sum(start, end - 1);

} else {

return end;

Common questions

Powered by AI

Method accessibility in Java is crucial as it determines which classes can use or invoke a particular method, aiding in encapsulation and security of code. Accessibility is controlled using access modifiers like public, private, and protected. Public methods can be accessed from any other class, whereas private methods are accessible only within the class they are declared, and protected methods are accessible within their package and subclasses .

In Java methods, parameters act as variables within the method and allow information to be passed into the method when it is called. These parameters are specified within parentheses following the method's name. For example, a method may be defined as static void myMethod(String fname, int age) where fname and age are parameters. When you call myMethod("Liam", 5), "Liam" and 5 are the arguments passed to the method .

Method overloading in Java allows multiple methods to have the same name with different parameters (either in number or type). This enhances functionality by enabling the same method to perform different tasks based on different input types. For example, static int plusMethod(int x, int y) can be overloaded as static double plusMethod(double x, double y). Both methods perform addition but handle different types (int and double) of input, thus making the code cleaner and more efficient .

The potential pitfall of using recursion is infinite recursion, where the function never stops calling itself, leading to a stack overflow error. This can be avoided by implementing a proper halting condition. For instance, in a recursive method to sum numbers, ensure the function returns a result without further recursion when a certain condition, such as reaching 0 or when the end is not greater than the start, is met .

The 'void' keyword in Java methods indicates that the method does not return any value. To modify a method to return a value, you replace 'void' with a return type such as int, char, etc., and include a return statement in the method body. For instance, changing a void method to static int myMethod(int x) { return 5 + x; } allows it to return an integer value .

In Java, the scope of variables determines their accessibility. Variables declared within a method are accessible only within that method (method scope). Variables defined inside a block of code (block scope), such as within curly braces {}, are accessible only within that block and following lines after their declaration. This limitation ensures variables are used only where needed and helps prevent naming conflicts and unintentional modifications .

Methods in programming, especially in Java, are used to perform certain actions and allow for code reuse. By defining a block of code once within a method, you can call it multiple times from different places in your program, thereby avoiding code duplication and making your code more manageable and organized .

Static methods belong to the class itself rather than any instance of the class, allowing them to be called without creating an instance. Instance methods, however, require an object of the class because they operate on the data within that object. Static methods are generally used for operations that do not require data from instances, thereby offering a slight performance advantage due to less overhead .

Recursion in Java breaks down complex problems into simpler sub-problems by creating a simpler instance of the same problem within a function. For example, to sum numbers from 1 to 10, the function sum(int k) can call itself with k-1 until k is 0, at which point recursion stops. This continuous breakdown of the problem simplifies the addition of a range of numbers into the trivial process of summing two numbers repeatedly .

A Java method can utilize multiple parameters by listing them in the method definition separated by commas. For example, static void myMethod(String fname, int age) takes two parameters: fname and age. When calling this method, you must provide two arguments, like myMethod("Liam", 5), where "Liam" is assigned to fname and 5 to age .

You might also like