Java Methods

JK 2006 
Created at
Updated at  
7,059 0 0

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:

public class Main {
  static void myMethod() {
    // code to be executed
  }
}

Example Explained

  • 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. 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:

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:

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!

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:

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

Multiple Parameters

You can have as many parameters as you like:

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

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:

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:

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):

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:

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:

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:

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:

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);
}

 

Tags Java Java Methods Java Parameters Method Overloading Facebook X
Comments 0
Similar posts
  1. Java Scope
    7,067
  2. Java Recursion
    7,176
  3. Java While Loop/Do While Loop/For Loop/For-Each Loop/Break/Continue
    7,800
  4. Java Classes and Objects
    7,056
  5. Java Switch Statements
    7,368
  6. Java Short Hand If...Else (Ternary Operator)
    7,532
  7. Java If ... Else
    7,358
  8. Java Packages
    7,150
  9. Java Inheritance (Subclass and Superclass)
    7,158
  10. Java Math
    7,403
  11. Java Variables
    7,416
  12. Java Comments
    7,955
  13. Java Polymorphism
    7,036
  14. The Print() Method
    7,131
  15. Java Syntax
    7,403
  16. Java Getting Started
    7,373
  17. Java Inner Classes
    7,023
  18. What is Java?
    7,071
  19. Machine Learning Types and Programming Languages
    7,204
  20. Java Tutorials associated with AP Computer Science A
    7,554
  21. Creating a simple Java Servlet (Web Server Page) with Apache Maven on Microsoft Windows
    7,144
  22. Java Servlet Example
    7,098
  23. Difference between Java and Javascript
    7,563
  24. Challenge: One Code Problem Per Day
    1,037
  1. Java Servlet Example
    7,098
  2. How do I replace content that based on the HTML UI Template
    7,133
  3. Creating a simple Java Servlet (Web Server Page) with Apache Maven on Microsoft Windows
    7,144
  4. Dataset of California Foodbanks
    7,144
  5. Java Tutorials associated with AP Computer Science A
    7,554
  6. Java Inner Classes
    7,023
  7. Java Polymorphism
    7,036
  8. Java Inheritance (Subclass and Superclass)
    7,158
  9. Java Packages
    7,150
  10. Java Abstract Classes and Methods
    7,669
  11. Java Classes and Objects
    7,056
  12. Java Recursion
    7,176
  13. Java Scope
    7,067
  14. Java Arrays
    8,604
  15. Java While Loop/Do While Loop/For Loop/For-Each Loop/Break/Continue
    7,800
  16. Java Switch Statements
    7,368
  17. Java Short Hand If...Else (Ternary Operator)
    7,532
  18. Java If ... Else
    7,358
  19. Java Math
    7,403
  20. Java Variables
    7,416
  21. Java Comments
    7,955
  22. The Print() Method
    7,131
  23. Java Syntax
    7,403
  24. Java Getting Started
    7,373
  25. What is Java?
    7,071
Recently updated
  1. The Complete Guide to Golang: History, Features, Real-World Uses, and Code Examples
    94
  2. Bootstrap vs. Tailwind CSS: Origins, Features, Pros & Cons, and How to Choose the Right Framework
    35
  3. Telemetry vs. Analytics: Understanding the Difference and Why It Matters
    164
  4. The Evolution and Production Reality of Agentic AI
    161
  5. How to Activate or Waive Your UIUC Student Health Insurance
    237
  6. Complete Guide to Building a Machine Learning Model
    281
  7. My life cuts at Las Vegas during Thanksgiving day holiday
    7,362
  8. The Cybercab Transformation: From Autonomous Taxi to Mobile Base Station
    307
  9. Harness vs. OpenClaw: Two Very Different "Agents"
    889
  10. Clean Python Environments: The Power of venv vs. Docker
    758
  11. What is Docker? Why is Docker also useful in a development environment?
    578
  12. UIUC 2026-2027 Academic Calendar
    1,453
  13. How to Build Llama 3 AI Apps with Python: Setup & User Prompts
    759
  14. Open-Source LLMs: The AI Revolution
    704
  15. Resume 2.0: Leveling Up for My First Software Gig
    2,057
  16. Not everyone will understand what this man just did
    1,712
  17. UIUC Dorm Guide: Find Your Perfect Fit !!
    1,543
  18. Unpacking IU's Shopper
    703
  19. Jackie Chan's Police Story: The Action Masterpiece
    601
  20. The IVE Story: Identity, 'I AM' Charts, and Influence
    901
  21. Tech Visionaries who graduated at UIUC - You are the Next Turn
    1,145
  22. Open Databases for Sex Crime Occurrences in the U.S.
    673
  23. Automatically copy text to the clipboard when dragging the mouse in the Cursor
    2,507
  24. My First Day at University of Illinois-Urvana Champaign
    1,154
  25. Sand, Sea, and a Splash of Fun at Newport Beach: A Family Adventure
    8,081
  26. Sun, Rocks, and Adventure: A Day at Joshua Tree National Park
    8,153
  27. Sipping the Stars: My Starbucks Adventure
    9,567
  28. Exciting explore at Sequoia National Park
    7,613
  29. My Life Shot at Death Valley
    1,617
  30. Ip Man fights with Muay Thai Master
    897
  31. Mad Clown - Don't Die
    971
  32. How to get Student Enrollment and Degree Verification at UIUC
    4,639
  33. LAX Thanksgiving Rush: A Joyful Reunion
    893
  34. ZO ZAZZ(조째즈) - Don`t you know (모르시나요) (PROD.ROCOBERRY)
    1,075
  35. FISHINGIRLS Unleashes Energetic EP 'Funiverse' Featuring Signature Track 'Fishing King'
    938
  36. 10CM - To Reach You (너에게 닿기를)
    1,122
  37. Feeling weak? Transform yourself at the UIUC ARC!
    1,544
  38. BOYNEXTDOOR - If I Say I Love You
    1,152
  39. The Future of Software Engineer - AI Engineering
    912
  40. G Dragon x Taeyang (Eyes Nose Lips, Power, Home Sweet Home, GOOD BOY) - LE GALA PIÈCES JAUNES 2025
    876
  41. Lie - Legend song by BIGBANG
    7,786
  42. Why ROLLBACK is useful when you work with Google Gemini CLI?
    804
  43. Reimbursement after Vaccination at McKinley Health Center
    970
  44. Gemini CLI makes a Magic! Time to speed up your app development with Google Gemini CLI!
    936
  45. Common Questions from UIUC school life in terms of CS Program
    1,068
  46. UIUC Immunization Compliance
    1,164
  47. LEE CHANHYUK's songs really resonate with my soul - Time Stop! Vivid LaLa Love, Eve, Endangered Love ...
    1,060
  48. LEE CHANHYUK - Endangered Love (멸종위기사랑)
    1,058
  49. Cupid (OT4/Twin Ver.) - LIVE IN STUDIO | FIFTY FIFTY (피프티피프티)
    841
  50. Common methods to improve coding skills
    956