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

Lecture 13 Methods

Uploaded by

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

Lecture 13 Methods

Uploaded by

hiraazhar2030
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 6

Java Methods

Object Oriented Programming in Java


Java Methods

• 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.
Method declaration
Declare a Method

• A method must be declared within a class. It is defined with the name


of the method, followed by parentheses ().
public class Person
{
static void myMethod()
{
// code to be executed
}
}

Explanation:
•myMethod() is the name of the method
•static means that the method belongs to the Main class and not an object of the Main
class.
•void means that this method does not have a return value.
Call a Method

• To call a method in Java, write the method's name followed by two


parentheses () and a semicolon;

public class Main


{
static void myMethod()
{
System.out.println("I just got executed!");
}
public static void main(String[] args)
{
myMethod();
}
}
A method can also be called multiple times:

public class Main


{
static void myMethod()
{
System.out.println("I just got
executed!");
}
public static void main(String[] args)
{
myMethod();
myMethod();
myMethod();
}
}

You might also like