Java Methods

JK JK 2026 
Created at
Updated at  
7,106 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,121
  2. Java Recursion
    7,209
  3. Java While Loop/Do While Loop/For Loop/For-Each Loop/Break/Continue
    7,908
  4. Java Classes and Objects
    7,109
  5. Java Switch Statements
    7,424
  6. Java Short Hand If...Else (Ternary Operator)
    7,601
  7. Java If ... Else
    7,417
  8. Java Packages
    7,189
  9. Java Inheritance (Subclass and Superclass)
    7,191
  10. Java Math
    7,455
  11. Java Variables
    7,490
  12. Java Comments
    8,058
  13. Java Polymorphism
    7,068
  14. The Print() Method
    7,174
  15. Java Syntax
    7,468
  16. Java Getting Started
    7,425
  17. Java Inner Classes
    7,077
  18. What is Java?
    7,108
  19. Machine Learning Types and Programming Languages
    7,263
  20. Java Tutorials associated with AP Computer Science A
    7,659
  21. Creating a simple Java Servlet (Web Server Page) with Apache Maven on Microsoft Windows
    7,188
  22. Java Servlet Example
    7,135
  23. Difference between Java and Javascript
    7,652
  24. Challenge: One Code Problem Per Day
    1,143
  1. How do I replace content that based on the HTML UI Template
    7,166
  2. Dataset of California Foodbanks
    7,189
  3. Java Abstract Classes and Methods
    7,770
  4. Java Arrays
    8,771
Recently updated
  1. Why You Can't Stop Watching Jack Bryan's Beatbox Gaming Shorts
    123
  2. Song So-hee: The Soulful Voice Touching Hearts Through Korean Music
    128
  3. Watch This Dazzling Dancer’s Mind-Blowing Moves
    158
  4. Michael Jackson's Billie Jean
    225
  5. Bootstrap vs. Tailwind CSS: Origins, Features, Pros & Cons, and How to Choose the Right Framework
    203
  6. The Complete Guide to Golang: History, Features, Real-World Uses, and Code Examples
    621
  7. Telemetry vs. Analytics: Understanding the Difference and Why It Matters
    320
  8. The Evolution and Production Reality of Agentic AI
    279
  9. How to Activate or Waive Your UIUC Student Health Insurance
    359
  10. Complete Guide to Building a Machine Learning Model
    389
  11. My life cuts at Las Vegas during Thanksgiving day holiday
    7,481
  12. The Cybercab Transformation: From Autonomous Taxi to Mobile Base Station
    416
  13. Harness vs. OpenClaw: Two Very Different "Agents"
    1,065
  14. Clean Python Environments: The Power of venv vs. Docker
    904
  15. What is Docker? Why is Docker also useful in a development environment?
    675
  16. UIUC 2026-2027 Academic Calendar
    1,709
  17. How to Build Llama 3 AI Apps with Python: Setup & User Prompts
    874
  18. Open-Source LLMs: The AI Revolution
    827
  19. Resume 2.0: Leveling Up for My First Software Gig
    2,411
  20. Not everyone will understand what this man just did
    2,012
  21. UIUC Dorm Guide: Find Your Perfect Fit !!
    1,663
  22. Unpacking IU's Shopper
    834
  23. Jackie Chan's Police Story: The Action Masterpiece
    713
  24. The IVE Story: Identity, 'I AM' Charts, and Influence
    1,022
  25. Tech Visionaries who graduated at UIUC - You are the Next Turn
    1,243
  26. Open Databases for Sex Crime Occurrences in the U.S.
    771
  27. Automatically copy text to the clipboard when dragging the mouse in the Cursor
    2,823
  28. My First Day at University of Illinois-Urvana Champaign
    1,252
  29. Sand, Sea, and a Splash of Fun at Newport Beach: A Family Adventure
    8,217
  30. Sun, Rocks, and Adventure: A Day at Joshua Tree National Park
    8,297
  31. Sipping the Stars: My Starbucks Adventure
    9,770
  32. Exciting explore at Sequoia National Park
    7,728
  33. My Life Shot at Death Valley
    1,793
  34. Ip Man fights with Muay Thai Master
    996
  35. Mad Clown - Don't Die
    1,094
  36. How to get Student Enrollment and Degree Verification at UIUC
    5,097
  37. LAX Thanksgiving Rush: A Joyful Reunion
    965
  38. ZO ZAZZ(조째즈) - Don`t you know (모르시나요) (PROD.ROCOBERRY)
    1,191
  39. FISHINGIRLS Unleashes Energetic EP 'Funiverse' Featuring Signature Track 'Fishing King'
    1,038
  40. 10CM - To Reach You (너에게 닿기를)
    1,210
  41. Feeling weak? Transform yourself at the UIUC ARC!
    1,621
  42. BOYNEXTDOOR - If I Say I Love You
    1,237
  43. The Future of Software Engineer - AI Engineering
    971
  44. G Dragon x Taeyang (Eyes Nose Lips, Power, Home Sweet Home, GOOD BOY) - LE GALA PIÈCES JAUNES 2025
    969
  45. Lie - Legend song by BIGBANG
    7,876
  46. Why ROLLBACK is useful when you work with Google Gemini CLI?
    907
  47. Reimbursement after Vaccination at McKinley Health Center
    1,074
  48. Gemini CLI makes a Magic! Time to speed up your app development with Google Gemini CLI!
    1,015
  49. Common Questions from UIUC school life in terms of CS Program
    1,183
  50. UIUC Immunization Compliance
    1,270