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.
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 System.out.println()
, but you can also create your own methods to perform certain actions:
Example
Create a method inside Main:
public class Main {
static void myMethod() {
// code to be executed
}
}
myMethod()
is the name of the methodstatic
means that the method belongs to the Main class and not an object of the Main 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 Main {
static void myMethod() {
System.out.println("I just got executed!");
}
public static void main(String[] args) {
myMethod();
}
}
// Outputs "I just got executed!"
A method can also be called multiple times:
Example
public class Main {
static void myMethod() {
System.out.println("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!
Java Method Parameters
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 Main { static void myMethod(String fname) { System.out.println(fname + " Refsnes"); } public static void main(String[] args) { myMethod("Liam"); myMethod("Jenny"); myMethod("Anja"); } } // Liam Refsnes // Jenny Refsnes // Anja Refsnes
When a parameter is passed to the method, it is called an argument. So, from the example above:fname
is a parameter, whileLiam
,Jenny
andAnja
are arguments.
Multiple Parameters
You can have as many parameters as you like:
Example
public class Main {
static void myMethod(String fname, int age) {
System.out.println(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
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 Main {
static int myMethod(int x) {
return 5 + x;
}
public static void main(String[] args) {
System.out.println(myMethod(3));
}
}
// Outputs 8 (5 + 3)
This example returns the sum of a method’s two parameters:
Example
public class Main {
static int myMethod(int x, int y) {
return x + y;
}
public static void main(String[] args) {
System.out.println(myMethod(5, 3));
}
}
// Outputs 8 (5 + 3)
You can also store the result in a variable (recommended, as it is easier to read and maintain):
Example
public class Main {
static int myMethod(int x, int y) {
return x + y;
}
public static void main(String[] args) {
int z = myMethod(5, 3);
System.out.println(z);
}
}
// Outputs 8 (5 + 3)
A Method with If…Else
It is common to use if...else
statements inside methods:
Example
public class Main {
// 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) {
System.out.println("Access denied - You are not old enough!");
// If age is greater than, or equal to, 18, print "access granted"
} else {
System.out.println("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 has 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);
System.out.println("int: " + myNum1);
System.out.println("double: " + myNum2);
}
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);
System.out.println("int: " + myNum1);
System.out.println("double: " + myNum2);
}
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 Main { public static void main(String[] args) { // Code here CANNOT use x int x = 100; // Code here can use x System.out.println(x);
}}
Block Scope
A block of code refers to all of the code 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:
Example
public class Main {
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
System.out.println(x);
} // The block ends here
// Code here CANNOT use x
}
}
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. 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 Main { public static void main(String[] args) { int result = sum(10); System.out.println(result);
}public static int sum(int k) { if (k > 0) { return k + sum(k - 1); } else { return 0;
}}
}
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 + ( 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 Main { public static void main(String[] args) { int result = sum(5, 10); System.out.println(result);
}public static int sum(int start, int end) { if (end > start) { return end + sum(start, end - 1); } else { return end; } } }
levofloxacin 500mg price buy levofloxacin pills
order avodart pills avodart pills order ondansetron 4mg generic
aldactone 25mg without prescription buy fluconazole 200mg generic fluconazole 200mg canada
purchase ampicillin online cheap order bactrim 480mg generic purchase erythromycin for sale
order sildenafil 50mg generic cheap methocarbamol methocarbamol tablet
order generic lamictal 200mg brand vermox 100mg retin gel brand
tadalis 10mg oral tadacip pills buy voltaren pills
order isotretinoin 40mg without prescription cost isotretinoin 10mg azithromycin cost
buy indocin 75mg pill buy indocin generic amoxicillin 500mg price
tadalafil 40mg price new cialis buy sildenafil 100mg online
arimidex price order arimidex 1mg generic buy sildenafil 100mg online
pharmacie en ligne cialis 40mg cialis en ligne viagra sans ordonnance en france
order deltasone 5mg pills canadian pharmacy cialis order viagra 100mg sale
cialis 5mg generika rezeptfrei kaufen original tadalafil 10mg rezeptfrei sicher kaufen original sildenafil 50mg rezeptfrei sicher kaufen
oral provigil 200mg Cialis no rx diamox 250mg generic
buy ramipril 5mg for sale temovate for sale online buy azelastine 10ml sprayer
purchase clonidine generic spiriva buy online order generic tiotropium bromide 9mcg
hytrin 1mg pills buy sulfasalazine without prescription buy azulfidine 500mg online cheap
order generic alendronate 70mg buy pepcid 20mg without prescription pepcid brand
buy benicar generic buy benicar without prescription buy acetazolamide 250mg generic
order generic tacrolimus 1mg brand tacrolimus order ursodiol 150mg pill
order isosorbide 20mg pills isosorbide medication telmisartan canada
order generic zyban 150 mg order generic strattera 10mg buy seroquel 50mg pills
molnupiravir 200 mg drug buy lansoprazole pill lansoprazole 30mg cheap
buy sertraline 50mg pills Order viagra without prescription sildenafil tablet
purchase imuran order imuran online viagra 100mg generic
tadalafil max dose Cialis for women sildenafil tablets
tadalafil cheap symmetrel online order symmetrel 100mg pill
dapsone 100mg oral brand nifedipine buy perindopril 8mg online
medroxyprogesterone 10mg for sale buy hydrochlorothiazide 25 mg online cheap buy periactin 4 mg online cheap
buy modafinil 200mg for sale order provigil generic ivermectin 50mg/ml
order luvox 100mg online cheap generic glucotrol 5mg glipizide without prescription
isotretinoin 20mg ca buy amoxil 250mg generic buy prednisone online
order piracetam generic nootropil canada order viagra without prescription
buy azithromycin 500mg online cheap buy zithromax 250mg generic gabapentin 100mg usa
cialis 5mg drug cialis order buy sildenafil generic
furosemide order online purchase doxycycline without prescription order hydroxychloroquine without prescription
order tadalafil 5mg sale buy betamethasone 20gm creams buy clomipramine pills
chloroquine canada order chloroquine 250mg order olumiant sale
Hello bro!Show more!..
http://bit.ly/3QIq0PD
порно 90
http://xianbaite.com/__media__/js/netsoltrademark.php?d=videoterebonka.com http://safeblaster.biz/__media__/js/netsoltrademark.php?d=videoterebonka.com http://alphaprime1.com/__media__/js/netsoltrademark.php?d=videoterebonka.com http://beneficialgreen.com/__media__/js/netsoltrademark.php?d=videoterebonka.com http://pngclimate.com/__media__/js/netsoltrademark.php?d=videoterebonka.com
https://drugsoverthecounter.com/# cvs over the counter covid test
https://over-the-counter-drug.com/# over the counter antidepressant
pills like viagra over the counter cvs united healthcare over the counter essentials
wellcare over the counter ordering best over the counter dark spot remover
https://over-the-counter-drug.com/# best over the counter diet pills
over the counter nausea medicine for pregnancy best over the counter cold medicine
over the counter ear wax removal over the counter pink eye drops
fluconazole over the counter rightsourcerx over the counter
https://over-the-counter-drug.com/# best over the counter toenail fungus treatment
ringworm treatment over the counter bronchial inhalers over the counter
https://over-the-counter-drug.com/# over the counter viagra
over the counter blood thinners over the counter muscle relaxers cvs
flonase over the counter over the counter laxatives
Hello bro!More info…
порно со сводной сестрой
гей порно корейцы
http://abbeyireland.com/__media__/js/netsoltrademark.php?d=pansionat-rnd.ru http://steelheadpredictor.com/__media__/js/netsoltrademark.php?d=pansionat-rnd.ru http://sschoppers.com/__media__/js/netsoltrademark.php?d=pansionat-rnd.ru http://spermnozzle.com/__media__/js/netsoltrademark.php?d=pansionat-rnd.ru http://coremanagementservices.com/__media__/js/netsoltrademark.php?d=pansionat-rnd.ru
anthem over the counter catalogue over the counter muscle relaxers cvs
zithromax for sale online cheap zithromax
https://stromectol.science/# ivermectin drug
doxycycline buy doxycycline without prescription uk
https://doxycycline.science/# buy cheap doxycycline
buy amoxil buy amoxicillin 500mg usa
doxycycline hyclate 100 mg cap 100mg doxycycline
https://doxycycline.science/# doxycycline 100mg
generic stromectol ivermectin buy australia
https://doxycycline.science/# buy doxycycline for dogs
zithromax 500 where can i get zithromax over the counter or zithromax 500mg
http://ecoserv.mobi/__media__/js/netsoltrademark.php?d=zithromax.science zithromax tablets
zithromax 500 mg lowest price online zithromax 1000 mg pills and zithromax online zithromax for sale cheap
amoxicillin no prescipion generic amoxicillin online
https://stromectol.science/# stromectol xr
buy zithromax zithromax tablets for sale
amoxicillin 500mg for sale uk order amoxil
https://zithromax.science/# zithromax cost uk
cheap zithromax zithromax drug
https://doxycycline.science/# online doxycycline
doxy 200 doxy
how to order doxycycline doxycycline 100 mg or generic doxycycline
http://inlieuof.net/__media__/js/netsoltrademark.php?d=doxycycline.science buy cheap doxycycline
doxycycline prices price of doxycycline and doxycycline tablets buy doxycycline monohydrate
amoxicillin 500 mg without a prescription amoxicillin 500mg for sale uk or amoxicillin online canada
http://remodeled.com/__media__/js/netsoltrademark.php?d=amoxil.science 875 mg amoxicillin cost
can i buy amoxicillin over the counter amoxicillin 500 mg tablet and amoxicillin price canada amoxicillin 500mg buy online canada
https://amoxil.science/# price of amoxicillin without insurance
order minocycline 100 mg online minocycline uses or ivermectin 0.08%
http://ww17.scbutton.com/__media__/js/netsoltrademark.php?d=stromectol.science buy minocycline 50 mg for humans
ivermectin gel cost of ivermectin 3mg tablets and ivermectin human minocycline 100mg otc
https://zithromax.science/# zithromax over the counter canada
zithromax zithromax online
buy amoxicillin amoxil for sale
https://zithromax.science/# zithromax online pharmacy canada
zithromax generic cost where can i get zithromax
100mg doxycycline generic for doxycycline
https://doxycycline.science/# doxycycline medication
generic amoxil online amoxicillin 500 mg brand name
zithromax 250 mg australia generic zithromax over the counter or zithromax 500mg over the counter
http://alexanwitherspreserve.net/__media__/js/netsoltrademark.php?d=zithromax.science where to buy zithromax in canada
where can i buy zithromax uk buy zithromax canada and zithromax coupon zithromax cost uk
doxycycline 150 mg doxycycline 200 mg or generic for doxycycline
http://ttgllc.com/__media__/js/netsoltrademark.php?d=doxycycline.science buy doxycycline online uk
doxycycline hyc doxycycline pills and doxycycline hyc 100mg doxycycline without a prescription
where can i get doxycycline doxycycline mono or doxycycline 500mg
http://piratenationoutfitters.com/__media__/js/netsoltrademark.php?d=doxycycline.science doxycycline 100mg online
generic doxycycline buy doxycycline online 270 tabs and buy doxycycline doxycycline mono
Long-Term Effects. Actual trends of drug.
ivermectin 200mg
Top 100 Searched Drugs. Drugs information sheet.
Read now. Long-Term Effects.
https://stromectolst.com/# ivermectin 1 cream generic
Everything what you want to know about pills. Best and news about drug.
Get information now. Everything about medicine.
https://stromectolst.com/# stromectol oral
Drug information. safe and effective drugs are available.
Generic Name. Read here.
https://stromectolst.com/# ivermectin 500mg
Drugs information sheet. Drugs information sheet.
Long-Term Effects. Some trends of drugs.
ivermectin 3
Learn about the side effects, dosages, and interactions. Everything about medicine.
Actual trends of drug. Prescription Drug Information, Interactions & Side.
ivermectin otc
п»їMedicament prescribing information. Everything what you want to know about pills.
minocycline 100 mg tablets minocycline or stromectol 3mg tablets
http://myflorida.us/__media__/js/netsoltrademark.php?d=stromectol.science ivermectin 12 mg
stromectol cvs ivermectin 1 cream generic and buy minocycline online ivermectin price
safe and effective drugs are available. Read now.
ivermectin 2%
Medicament prescribing information. Best and news about drug.
ivermectin pill cost stromectol ivermectin or ivermectin online
http://collectorcarfinders.com/__media__/js/netsoltrademark.php?d=stromectolst.com ivermectin 250ml
ivermectin 4 tablets price cost of ivermectin cream and ivermectin 1 ivermectin 4000 mcg
ivermectin coronavirus ivermectin 3mg tablets price or ivermectin over the counter canada
http://global-light-network.com/__media__/js/netsoltrademark.php?d=stromectolst.com ivermectin generic
stromectol 3mg ivermectin tablets and ivermectin 1% cream generic stromectol pill
ivermectin rx ivermectin 50 mg or stromectol 3mg
http://articlesonhearing.com/__media__/js/netsoltrademark.php?d=stromectolst.com ivermectin human
ivermectin 8000 stromectol for humans and ivermectin 5 stromectol for humans